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.
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
Checking if a string has some set of characters or not We can use a character class which lets us define a range of characters for the match. For example, if we want to search for vowel, we can use [aeiou] for match.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With