2010-11-04 14 views
3

我想從數值範圍生成(一系列)正則表達式。從數值範圍生成正則表達式

例子:

1013 - 4044 => 

regexp      matches 
--------------------------------------- 
101[3-9]     1013 - 1019 
10[2-9][0-9]    1020 - 1099 
11[0-9][0-9]    1100 - 1199 
[23][0-9][0-9][0-9]   2000 - 3999 
40[0-3][0-9]    4000 - 4039 
404[0-4]     4040 - 4044 

什麼是最簡單的算法?

反轉它的最簡單方法是什麼(即給定正則表達式,查找範圍)?

會很高興地看到在Java中,Clojure中,perl的解決方案......

謝謝!

+2

就在五分鐘前,有人張貼在什麼可以而且應該用正則表達式來完成一個偉大的答案,什麼不應該:http://stackoverflow.com/questions/4098086/to-use-or-not -40-使用正則表達式/ 4098123#4098123(Spoiler:這屬於後一類) – delnan 2010-11-04 20:34:40

+0

^像delnan說的,再加上你忘了'1200-1999'的範圍。你最好從textblob中提取所有整數序列,並用其他方法進一步處理它們。 – Wrikken 2010-11-04 20:44:28

回答

2

有一個online tool給定範圍生成正則表達式,並提供解釋。你也可以在那裏找到源代碼。例如:

^(101[3-9]|10[2-9][0-9]|1[1-9][0-9]{2}|[23][0-9]{3}|40[0-3][0-9]|404[0-4])$ 
 
First, break into equal length ranges: 
    1013 - 4044 

Second, break into ranges that yield simple regexes: 
    1013 - 1019 
    1020 - 1099 
    1100 - 1999 
    2000 - 3999 
    4000 - 4039 
    4040 - 4044 

Turn each range into a regex: 
    101[3-9] 
    10[2-9][0-9] 
    1[1-9][0-9]{2} 
    [23][0-9]{3} 
    40[0-3][0-9] 
    404[0-4] 

Collapse adjacent powers of 10: 
    101[3-9] 
    10[2-9][0-9] 
    1[1-9][0-9]{2} 
    [23][0-9]{3} 
    40[0-3][0-9] 
    404[0-4] 

Combining the regexes above yields: 
    (101[3-9]|10[2-9][0-9]|1[1-9][0-9]{2}|[23][0-9]{3}|40[0-3][0-9]|404[0-4]) 

Next we'll try factoring out common prefixes using a tree: 
Parse into tree based on regex prefixes: 
    . 1 0 1 [3-9] 
     + [2-9] [0-9] 
    + [1-9] [0-9]{2} 
    + [23] [0-9]{3} 
    + 4 0 [0-3] [0-9] 
     + 4 [0-4] 

Turning the parse tree into a regex yields: 
    (1(0(1[3-9]|[2-9][0-9])|[1-9][0-9]{2})|[23][0-9]{3}|40([0-3][0-9]|4[0-4])) 

We choose the shorter one as our result. 

^(101[3-9]|10[2-9][0-9]|1[1-9][0-9]{2}|[23][0-9]{3}|40[0-3][0-9]|404[0-4])$ 

扭轉它,你可以看看字符類,並得到各方案的最小值和最大值。

^(101[3-9]|10[2-9][0-9]|1[1-9][0-9]{2}|[23][0-9]{3}|40[0-3][0-9]|404[0-4])$ 
=> 1013  1020   1100   2000  4000   4040  lowers 
     1019   1999  1199   3999   4039  4044 uppers 

=> 1013 - 4044 
+2

在線工具需要驗證,你有什麼? – 2015-12-16 09:24:11

+0

是煩人我也無法得到它:( – Wez 2016-01-12 04:56:45

+0

無法訪問該在線工具,它需要認證......但根據這[腳本](http://code.activestate.com/recipes/534137-generate -a-regular-expression-to-match-an-arbitrar /),這與它應該在引用的工具中可用相同 – sirboderafael 2016-07-10 04:47:57