Skip to content Skip to sidebar Skip to footer

Why Doesn't This Regular Expression Work The Way I Want It?

I'm trying to make the regular expression find the numbers in a date string (eg, 04/05/1989). This is what I have: \A0[1-9]{2}\/0[1-9]{2}\/[1900-2012]\z

Solution 1:

The square brackets create a character range, not a number range:

  • [A-Z] matches all ASCII characters from A to Z.
  • [1900-2012] matches the 1, the 9, the 0, the range of ASCII characters between 0 and 2, the 0, the 1 and the 2. Effectively the same can be expressed as [0-29].

Within a character range expression, the order of characters is not important. [0815] is the same as [8510]. Hence [1900] is the same as [019].

You want (19[0-9]{2}|200[0-9]|201[0-2]) to match the correct year range. Or, if you just want to match four digits and don't want range validation you can use ([0-9]{4})

Same for month and day. You can do it with range validation or you can do it by matching one or two digits. I'd recommend the latter.

^([0-9]{1,2})/([0-9]{2})/([0-9]{4})$

Try to convert the result to a date value. If that fails, the input was invalid. If it succeeds, check if the resulting date falls into your required range. Regex is the wrong tool to provide date validity checks.

Solution 2:

I had answered a similar question over here: How to parse a date in format "YYYYmmdd" in JavaScript?. It just needs some modifications in the extraction part.

EDIT: You could modify that function this way:

functionparse(str) {    // str format: 'dd/mm/yyyy'var d = str.substr(0,2),
        m = parseInt(str.substr(3,2)) - 1,
        y = str.substr(6,4);
    var D = newDate(y,m,d);
    return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}

Solution 3:

(?<!\d)((0?\d)|([12]\d)|(3[01]))/((0?\d)|(1[0-2]))/((19)|(20))\d\d

Seems to work in the tests I did.

(?<!\d)((((0?\d)|([12]\d)|(3[01]))/(((0?((1[02]?)|([3578]))))|(1[0-2])))|(((0?\d)|([12]\d))/(0?2))|(((0?\d)|([12]\d)|(30))/((0?[2469])|(11))))/((19)|(20))\d\d

The previous regex matches invalid dates like 31/02/2012 but this ones seems a little more normative.

Solution 4:

IMHO this won't match valid 10/10/1989 but will match invalid 099/0991989. First of all 0[1-9]{2} matches 0 plus two digits between 1 and 9. Also [1900-2012] is not what you want.

Solution 5:

try this

\A[0-9]{2}\/[0-9]{2}\/[1900-2012]\z

it should match dates in format dd/mm/yyyy(1900 to 2012)

Post a Comment for "Why Doesn't This Regular Expression Work The Way I Want It?"