开发者

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

开发者 https://www.devze.com 2022-12-20 05:22 出处:网络
How do I a string against a regex such that it will return true if the whole string matches (not a substring)?

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

精彩评论

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

关注公众号