dublintech
dublintech

Reputation: 17795

Regular expression for numeric range

Looking for a regular expression to cover a number range. More specifically, consider a numeric format:

NN-NN

where N is a number. So examples are:

04-11
07-12
06-06

I want to be able to specify a range. For example, anything between:

01-27 and 02-03

When I say range, it is as if the - is not there. So the range: the range 01-27 to 02-03

would cover: 01-28, 01-29, 01-30, 01-31 and 02-01

I want the regular expression so that I can plug in values for the range very easily. Any ideas?

Upvotes: 1

Views: 341

Answers (3)

Junuxx
Junuxx

Reputation: 14281

'0[12]-[0-3][1-9]' would match all of the required dates, however, it would also match dates like 01-03. If you want to match exactly and only the dates in that range, you'll need to do something a little more advanced.

Here's an easily configurable example in 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 looks like this:

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

And the output is:

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

Upvotes: 1

buckley
buckley

Reputation: 14129

Validating dates is not where regexes strengths are.

for example, how would you validate February regarding leap years.

The solution is to use the available date API's in your language

Upvotes: 2

ioseb
ioseb

Reputation: 16949

It's not completely clear for me, and you didn't mention language as well, but in PHP it looks like this:

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

Do you have any use case so we can adjust code to your needs?

Upvotes: 0

Related Questions