我有2个字符串:
I have 4 cars in my house
I have 14 cars in my house
我们如何使用ruby(1.9.3)正则表达式来检查只有1到10辆汽车匹配?
例如:
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
另外,我们如何匹配(即2辆车)任何字符串?因此,如果目标字符串包含' 22辆汽车'然后它不应该匹配。
例如:
some other string before 2 cars some other string after # => match
some other string before 22 cars some other string after # => should not match
答案 0 :(得分:2)
使用此RegExp:/I have ([1-9]|10) cars? in my house./
[1-9]
创建1,2,3,4,5,6,7,8,9的范围,管道字符作为or
使用,以允许10个。括号为捕获组。汽车末端's'后面的问号意味着“零或一个前置字符”,因此匹配“汽车”和“汽车”。希望这有帮助!
答案 1 :(得分:1)
正则表达式:/I have (?:1 car|[2-9] cars|10 cars) in my house/
(?:xxx)使括号不捕获如here所述。