tags:

views:

59

answers:

2

Hey,

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.

+5  A: 

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

>> "a\na" =~ /^a$/
=> 0
>> "a\na" =~ /\Aa\Z/
=> nil
>> "a\na" =~ /\Aa\na\Z/
=> 0
Tomas Markauskas
+5  A: 

So, what you are asking is how to test whether the two strings are equal, right? Just use string equality! This passes every single one of the examples that both you and Tomas cited:

'ee'   == 'street' # => false
'ee'   == 'ee'     # => true
"a\na" == 'a'      # => false
"a\na" == "a\na"   # => true
Jörg W Mittag
This is true, but a regular expression also allows you to expand your definition of 'equal' to things like /^(ee|oo)$/ pretty nicely.
doctororange