Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to find an exact pattern match in Ruby

Tags:

regex

ruby

How would I go about testing for an exact match using regex.

"car".match(/[ca]+/) returns true.

How would I get the above statement to return false since the regex pattern doesn't contain an "r"? Any string that contains any characters other than "c" and "a" should return false.

"acacaccc" should return true

"acacacxcc" should return false

like image 674
Tim Avatar asked Jul 15 '11 23:07

Tim


2 Answers

Add some anchors to it:

/^[ca]+$/
like image 198
sidyll Avatar answered Sep 16 '22 13:09

sidyll


You just need anchors.

"car".match(/^[ca]+$/)

This'll force the entire string to be composed of "c" or "a", since the "^" and "$" mean "start" and "end" of the string. Without them, the regex will succeed as long as it matches any portion of the string.

like image 40
Chris Heald Avatar answered Sep 19 '22 13:09

Chris Heald