How do I test a WHOLE string against regex in ruby?

How do I a string against a regex such that it will return true if the whole string matches (not a substring)?

eg:

test( \ee\ , "street" ) #=> returns false
test( \ee\ , "ee" ) #=> returns true!

Thank you.


You can match the beginning of the string with \A and the end with \Z. In ruby ^ and $ match also the beginning and end of the line, respectively:

>> "a\na" =~ /^a$/
=> 0
>> "a\na" =~ /\Aa\Z/
=> nil
>> "a\na" =~ /\Aa\na\Z/
=> 0

This seems to work for me, although it does look ugly (probably a more attractive way it can be done):

!(string =~ /^ee$/).nil?

Of course everything inside // above can be any regex you want.

Example:

>> string = "street"
=> "street"
>> !(string =~ /^ee$/).nil?
=> false
>> string = "ee"
=> "ee"
>> !(string =~ /^ee$/).nil?
=> true

Note: Tested in Rails console with ruby (1.8.7) and rails (3.1.1)