Ruby正则表达式匹配的字符串以数字范围开头



我有两个字符串:

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

我们如何使用ruby(1.9.3)regex来检查只有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    

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

[1-9]创建1、2、3、4、5、6、7、8、9的范围,管道角色充当or以允许10。括号是一个捕获组。汽车末尾的"s"后面的问号表示"前一个字符的零或一",因此与"汽车"one_answers"汽车"都匹配。希望这能有所帮助!

正则表达式:/I have (?:1 car|[2-9] cars|10 cars) in my house/

你可以在http://rubular.com/

(?:xxx)使括号不捕获,如这里所述。

最新更新