Why does this regular expression become true in ruby?

I started learning regular expressions in ruby. I had one problem with this. The problem is that the regex below does not work as expected.

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

For instance,

str = "      

        abc

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

My expectation is that this condition will be false. But that is becoming true. I do not know why?

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

+4
source share
1 answer

The reason is that in Ruby ^and regex $correspond to the beginning / end of the line. Go to \Aand \z, and you will get the result false.

Ruby Ideone. /\A\s*\z/ , , .

\s, [ \t\r\n\f], [ \t\n]. . Ruby:

/\s/ - : /[ \t\r\n\f]/

+4

Source: https://habr.com/ru/post/1648459/


All Articles