开发者

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开发者_Python百科( \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)


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜