简体   繁体   中英

Using regex to find an exact pattern match in 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

Add some anchors to it:

/^[ca]+$/

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.

Turn your logic around and look for bad things:

string.match(/[^ca]/)
string.index(/[^ca]/)

If either of the above are non-nil, then you have a bad string. If you just want to test and don't care about where it matches then:

if string.index(/[^ca]/).nil?
    # You have a good string
else
    # You have a bad string

For example:

>> "car".index(/[^ca]/).nil?
=> false
>> "caaaacaac".index(/[^ca]/).nil?
=> true

try this

"car".match /^(a|c)+$/

Try this:

"car".match(/^(?:c|a)$/)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM