gpt4 book ai didi

Ruby 正则表达式匹配字符串前面有数字范围

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:43 24 4
gpt4 key购买 nike

我有 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

最佳答案

使用这个正则表达式:/I have ([1-9]|10) cars?在我家。/

[1-9] 创建范围 1,2,3,4,5,6,7,8,9 并且竖线字符作为 or 允许 10。括号是捕获组。 cars 末尾的“s”后面的问号表示“零个或一个前面的字符”,因此与“car”和“cars”都匹配。希望这对您有所帮助!

关于Ruby 正则表达式匹配字符串前面有数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com