简体   繁体   中英

Ruby regex matching string precede with range of numbers

I have 2 strings:

I have 4 cars in my house
I have 14 cars in my house

How do we use ruby (1.9.3) regex to check only 1 to 10 car are matched?

Ex:

I have 1 car in my house # => match
I have 4 cars in my house # => match
I have 10 cars in my house # => match
I have 14 cars in my house # => should not match
I have 100 cars in my house # => should not match

Also, how do we match (ie 2 cars) against any strings? so that if the target string contains '22 cars' then it should not match.

Ex:

some other string before 2 cars some other string after # => match
some other string before 22 cars some other string after # => should not match    

Use this RegExp: /I have ([1-9]|10) cars? in my house./ /I have ([1-9]|10) cars? in my house./

The [1-9] creates a range of 1,2,3,4,5,6,7,8,9 and the pipe character acts as an or to allow for 10. The parenthesis are a capture group. The question mark after the 's' at the end of cars means "zero or one of the preceeding character" and therefore matches both 'car' and 'cars'. Hope this helped!

Regular expression: /I have (?:1 car|[2-9] cars|10 cars) in my house/

You can try that interatively at http://rubular.com/

The (?:xxx) makes parenthesis non-capturing as stated here .

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