suresh suresh - 4 months ago 8
Ruby Question

Why this regular expression gets true in ruby?

I was started learning the regular expressions in ruby. In that I had one problem. The problem is the below regular expression does not work as expected.

/^[\s]*$/ -- This will match only if the input contains white spaces or the input contains empty.


For example,

str = "

abc

"
if str =~ /^[\s]*$/
puts "Condition is true"
else
puts "Condition is false"
end


My expectation is this condition will gets false. But it gets true. I don't know why ?

In sed or grep it will work as expected. But why it does not works in ruby.

Answer

The reason is that in Ruby regex, ^ and $ match the start/end of a line. Change to \A and \z and you will get a false result.

See this Ruby demo at Ideone. The /\A\s*\z/ will only match strings that are either empty or have whitespace symbols only.

As for \s, it is a synonym for [ \t\r\n\f], not just [ \t\n]. See this Ruby Character Class reference:

/\s/ - A whitespace character: /[ \t\r\n\f]/

Comments