Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

regex

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( \ee\ , "street" ) #=> returns false test( \ee\ , "ee" ) #=> returns true! 

Thank you.

like image 931
doctororange Avatar asked Feb 10 '10 12:02

doctororange


People also ask

How do I check a string in RegEx?

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.

How do you match a string in Ruby?

=~ 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.

How do I check if a regular expression is Ruby?

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.


2 Answers

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 
like image 74
Tomas Markauskas Avatar answered Oct 08 '22 12:10

Tomas Markauskas


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)

like image 39
Brian Cordeiro Avatar answered Oct 08 '22 11:10

Brian Cordeiro