2012-06-11 138 views
1

尋找一個包含數字範圍的正則表達式。更具體地說,考慮數字格式:數字範圍的正則表達式

NN-NN 

其中N是一個數字。因此示例如下:

04-11 
07-12 
06-06 

我希望能夠指定範圍。例如,任何事情之間:

01-2702-03

當我說的範圍,這是因爲如果-是不存在的。所以範圍: 範圍01-2702-03

將涵蓋: 01-28, 01-29, 01-30, 01-3102-01

我想正則表達式,這樣我可以在插入值的範圍變得非常容易。有任何想法嗎?

+1

什麼正則表達式風味您使用的?看到這個[鏈接](http://www.regular-expressions.info/numericranges.html)爲insiration –

+1

所以這些是日期?否則,「01-32」沒有包括在內的解釋是什麼?你不能(或不應該)單獨使用正則表達式來完成。 –

+1

這些日期?如果是這樣,你不想使用正則表達式來驗證它們。請使用您的語言中的日期庫/工具。 – Qtax

回答

0

這對我來說並不完全清楚,而且你沒有提到的語言爲好,但在PHP它看起來像這樣:

if (preg_match('~\d{2}-\d{2}~', $input, $matches) { 
// do something here 
} 

你有任何使用情況下,所以我們可以調整代碼以您的需求?

2

驗證日期不是正則表達式的優點。

例如,如何驗證2月份的閏年。

的解決方案是使用現有的日期API在你的語言

+0

不試圖驗證日期。日期在文件名中。我只想挑選一個日期之後和另一個日期之前的文件。 – dublintech

+0

在正則表達式組中捕獲兩個數字,然後將發現的數字字符串轉換爲數字類型並比較數字。 –

1

'0[12]-[0-3][1-9]'會匹配所有需要的日期,但是,它也將匹配日期像01-03。如果您想要精確匹配並且只匹配該範圍內的日期,那麼您需要做一些更高級的操作。

下面是一個Python易於配置的例子:

from calendar import monthrange 
import re 

startdate = (1,27) 
enddate = (2,3) 

d = startdate 
dateList = [] 

while d != enddate: 
    (month, day) = d 
    dateList += ['%02i-%02i' % (month, day)] 
    daysInMonth = monthrange(2011,month)[1] # took a random non-leap year 
          # but you might want to take the current year 
    day += 1 
    if day > daysInMonth: 
     day = 1 
     month+=1 
     if month > 12: 
      month = 1 
    d = (month,day) 

dateRegex = '|'.join(dateList) 

testDates = ['01-28', '01-29', '01-30', '01-31', '02-01', 
       '04-11', '07-12', '06-06'] 

isMatch = [re.match(dateRegex,x)!=None for x in testDates] 

for i, testDate in enumerate(testDates): 
    print testDate, isMatch[i] 

dateRegex看起來是這樣的:

'01-27|01-28|01-29|01-30|01-31|02-01|02-02' 

,輸出是:

01-28 True 
01-29 True 
01-30 True 
01-31 True 
02-01 True 
04-11 False 
07-12 False 
06-06 False