Skip to main content
 首页 » 编程设计

regex之如何使用正则表达式匹配 X 和 Y 之间的数字

2024年11月24日24oomusou

我想用 RegEx 匹配 X 和 Y 之间的数字。这可能吗?
([0-9]+) 将匹配任何数字,我该怎么做才能匹配 110 和 2234 之间的数字?

请您参考如下方法:

根据 Generate a Regular Expression to Match an Arbitrary Numeric Range ,并在 Regex_For_Range 为您的示例生成这样的正则表达式后:

\b0*(1[1-9][0-9]|[2-9][0-9]{2}|1[0-9]{3}|2[01][0-9]{2}|22[0-2][0-9]|223[0-4])\b 

会做的伎俩。

该过程将是(仍然遵循该正则表达式生成器):

First, break into equal length ranges:


110 - 999 
1000 - 2234 

Second, break into ranges that yield simple regexes:


110 - 199 
200 - 999 
1000 - 1999 
2000 - 2199 
2200 - 2229 
2230 - 2234 

Turn each range into a regex:


1[1-9][0-9] 
[2-9][0-9]{2} 
1[0-9]{3} 
2[01][0-9]{2} 
22[0-2][0-9] 
223[0-4] 

Collapse adjacent powers of 10: 1[1-9][0-9] [2-9][0-9]{2} 1[0-9]{3} 2[01][0-9]{2} 22[0-2][0-9] 223[0-4]

Combining the regexes above yields:


0*(1[1-9][0-9]|[2-9][0-9]{2}|1[0-9]{3}|2[01][0-9]{2}|22[0-2][0-9]|223[0-4]) 

Next we'll try factoring out common prefixes using a tree:
Parse into tree based on regex prefixes:


. 1 [1-9] [0-9] 
+ [0-9]{3} 
+ [2-9] [0-9]{2} 
+ 2 [01] [0-9]{2} 
+ 2 [0-2] [0-9] 
+ 3 [0-4] 

Turning the parse tree into a regex yields:


0*(1([1-9][0-9]|[0-9]{3})|[2-9][0-9]{2}|2([01][0-9]{2}|2([0-2][0-9]|3[0-4]))) 

We choose the shorter one as our result.


\b0*(1[1-9][0-9]|[2-9][0-9]{2}|1[0-9]{3}|2[01][0-9]{2}|22[0-2][0-9]|223[0-4])\b