How to check WHOLE string for regular expression in ruby?

Like a regex string so that it returns true if the string integer matches (and not a substring)?

eg:

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

Thank.

+41
string ruby regex
Feb 10 '10 at 12:20
source share
3 answers

You can combine the beginning of a line with \A and the end with \Z In ruby ​​^ and $ beginning and end of the line also correspond:

 >> "a\na" =~ /^a$/ => 0 >> "a\na" =~ /\Aa\Z/ => nil >> "a\na" =~ /\Aa\na\Z/ => 0 
+60
Feb 10 2018-10-10
source share

This seems to work for me, although it looks ugly (perhaps in a more attractive way, this can be done):

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

Of course, everything inside // above can be any regular expression 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)

+15
Dec 13 2018-11-11T00:
source share

So what are you asking, how to check if two strings are equal, right? Just use string equality! This goes through each of the examples quoted by you and Thomas:

 'ee' == 'street' # => false 'ee' == 'ee' # => true "a\na" == 'a' # => false "a\na" == "a\na" # => true 
+6
Feb 10 '10 at
source share



All Articles