suresh suresh - 1 year ago 49
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 = "


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

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.


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]/