Thursday, February 17, 2011

Regex - is there something I've done wrong?

This is javascript, but a virtually identical regex is failing in PHP too, so I don't think it's language specific

var r = new RegExp(
    "^(:19|20)?[0-9][0-9]"            // optional 19/20 start followed by 2 numbers
    + "-"                             // a hyphen
    + "(:0?[1-9]|1[0-2])"             // optional 0 followed by 1-9, or 10, 11, 12
    + "-"                             // a hyphen
    + "(:3[01]|[12][0-9]|0?[1-9])$"   // you get the idea.
);
r.test("2008-07-01");                // == false

What on earth am I missing?

From stackoverflow
  • I think your non-capturing blocks should be e.g. (?:19|20) rather than (:19|20)

    nickf : that was it, cheers.
  • Correct; your regular expression would actually work with "?:"

    "?" when used a prefix indicates that you're going to do something about capturing. Either not capture the block (":"), capture ahead ("="), behind ("<="), etc.

0 comments:

Post a Comment