Reputation: 139
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 (i.e. 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
Upvotes: 1
Views: 1850
Reputation: 3088
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.
Upvotes: 1
Reputation: 2514
Use this RegExp: /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!
Upvotes: 2