如何使用正则表达式匹配 X 和 Y 之间的数字? [英] How to match numbers between X and Y with regexp?

查看:39
本文介绍了如何使用正则表达式匹配 X 和 Y 之间的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 RegExp 匹配 X 和 Y 之间的数字.这可能吗?

([0-9]+) 将匹配任何数字,我该怎么做才能匹配 110 和 2234 之间的数字?

解决方案

根据生成正则表达式以匹配任意数字范围,并在 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

会成功.

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

<块引用>

首先,分成相等的长度范围:

110 - 9991000 - 2234

<块引用>

其次,分解产生简单正则表达式的范围:

110 - 199200 - 9991000 - 19992000 - 21992200 - 22292230 - 2234

<块引用>

将每个范围转换为正则表达式:

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]

<块引用>

折叠相邻的 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]

结合上面的正则表达式产生:

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])

<块引用>

接下来,我们将尝试使用树来分解常见前缀:
根据正则表达式前缀解析成树:

<预><代码>.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]

<块引用>

将解析树转换为正则表达式:

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])))

<块引用>

我们选择较短的一个作为我们的结果.

\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

I would like to match with RegExp a number between X and Y. Is that possible?

([0-9]+) will match any number, how could I do to match a number between, for instance, 110 and 2234?

解决方案

According to Generate a Regular Expression to Match an Arbitrary Numeric Range, and after generating such a regex for your example at 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

would do the trick.

The process would be (still following that Regex generator):

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

这篇关于如何使用正则表达式匹配 X 和 Y 之间的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆