What is a Ruby regex to match a string with at least one period and spaces?

What is a regular expression to match a string with at least one period and spaces?

+4
source share
4 answers

You can use this:

/^\S*\.\S*$/ 

It works as follows:

 ^ <-- Starts with \S <-- Any character but white spaces (notice the upper case) (same as [^ \t\r\n]) * <-- Repeated but not mandatory \. <-- A period \S <-- Any character but white spaces * <-- Repeated but not mandatory $ <-- Ends here 

You can replace \S with [^ ] to work strictly with spaces (not with tabs, etc.)

+13
source

Sort of

  ^[^ ]*\.[^ ]*$ 

(match any non-spaces, then period, then a few more spaces)

+2
source

no need for regular expression. Keep it simple

 >> s="test.txt" => "test.txt" >> s["."] and s.count(" ")<1 => true >> s="test with spaces.txt" => "test with spaces.txt" >> s["."] and s.count(" ")<1 => false 
+2
source

Try the following:

 /^\S*\.\S*$/ 
0
source

All Articles