bulltorious
bulltorious

Reputation: 7897

.Net Regex for mm-dd-yy and others + yyymmdd

I feel like I am chasing my tail.

I am trying to arrive at a .Net regex that will match on the following:

mm-dd-yy
m-dd-yy
mm-d-yy
m-d-yy

and (no dashes)

yyyymmdd

Upvotes: 0

Views: 682

Answers (4)

Skurmedel
Skurmedel

Reputation: 22149

Well it all comes down to how strict you want the matching to be.

[0-9]+\-[0-9]+\-[0-9]+ 

will match all the four top ones. But you can enter "99-99-99".

You can be a bit more strict with:

([0-1][0-2]|[0-9])\-(3[0-1]|[0-2]?[0-9]+)\-[0-9]{1,2}

This will only match dates where each component is in a valid range, but only to an extent. It would still match a February with 31 days (which it won't have in the Gregorian calendar). Also it will match 13-04-18 from 3 and onwards. You can use anchors to make it match the whole text (add ^ at the beginning and $ at the end of the regex), but then it won't be able to find the dates inside a text.

You can add a precondition to make sure there's no weird digits around it though. Negative look-behind and negative look-ahead.

(?<![0-9])([0-1][0-2]|[0-9])\-(3[0-1]|[0-2]?[0-9]+)\-[0-9]{1,2}(?![0-9])

And so forth, but this regex has already become a proper behemoth. I would go with the second or third version and use DateTime.Parse to validate it.

There's only so far you can go with regex for dates before they become write-once and insane :) (what about leap years for example, etc. etc.)

Upvotes: 0

Mark Avenius
Mark Avenius

Reputation: 13947

Do you need to use Regex, or do you just care that it is a valid date?

    DateTime result;
    if(DateTime.TryParse(input, out result))
    {
        // you have your date in result
    }

Upvotes: 0

dtb
dtb

Reputation: 217313

One or two digits followed by a dash, followed by one or two digits, followed by a dash, follows by to digits or eight digits:

(\d{1,2}-\d{1,2}-\d{2})|(\d{8})

Upvotes: 1

theChrisKent
theChrisKent

Reputation: 15099

A very simple RegEx that just matches to the digits being in the correct places and matches all your formats:

^[0-9]{1,2}-[0-9]{1,2}-[0-9]{2}$|^[0-9]{8}$

This does not validate those dates as actual possible dates, to do this you would be better off using DateTime.TryParse

Upvotes: 1

Related Questions