3

Trying to write a regex expression in C# that accepts any/all of the following:

  1. 02/01/1968
  2. 2/01/1968
  3. 2/1/1968

(This question is somewhat different then other similar questions in that this is to be a single word, in mm/dd/yyyy format. Only the pattern is needed without verification as to its possibility. i.e., 99/99/9999 is o.k.)

I am getting nowhere fast. Here is as far as I've gotten (which only recognizes 02/01/1968):

Regex regex = new Regex(@"^\d{2}/\d{2}/\d{4}$",RegexOptions.IgnorePatternWhitespace);
Match x = regex.Match(birthdate);
if (x.Success == false) return;

Thanks for any help. (An explanation with the regex would be most appreciated).

3
  • @"^\d{1,2}/\d{1,2}/\d{4}$"
    – EZI
    Commented Aug 4, 2015 at 18:59
  • 5
    You'll be better off using DateTime.TryParseExact.
    – juharr
    Commented Aug 4, 2015 at 18:59
  • 1
    Please don't compare booleans to true and false. Change if (x.Success == false) return; to if (!x.Success) return;
    – ErikE
    Commented Aug 4, 2015 at 19:06

4 Answers 4

15

As mentioned in comments, use a datetime parser. To get the right regex(returning only valid datetimes) can be very complex and hard to maintain.

var formats = new[] { "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(input, formats, null, DateTimeStyles.None, out dt))
{
    //parsed correctly
}

BTW: It is not clear in your question whether you want dd/mm or mm/dd, I chose the first one

3
  • Looking for mm/dd/yyyy. Thanks.
    – Alan Wayne
    Commented Aug 4, 2015 at 20:11
  • @AlanWayne then formats would be var formats = new[] { "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy", "MM/dd/yyyy" };
    – Eser
    Commented Aug 4, 2015 at 20:16
  • 2
    This IS better, but I'm trying to learn regex pattern matching. Thanks. :)
    – Alan Wayne
    Commented Aug 4, 2015 at 20:40
5

Here's a regex that checks the right number of days per month, including for February during leap years:

var reg = new Regex(@"\b(((0?[469]|11)/(0?[1-9]|[12]\d|30)|(0?[13578]|1[02])/(0?[1-9]|[12]\d|3[01])|0?2/(0?[1-9]|1\d|2[0-8]))/([1-9]\d{3}|\d{2})|0?2/29/([1-9]\d)?([02468][048]|[13579][26]))\b", RegexOptions.ECMAScript | RegexOptions.ExplicitCapture);

Breaking up the regex this way should be easy to understand:

  • Months with 30 days: 0?[469]|11

  • Days maxed at 30: 0?[1-9]|[12]\d|30

  • Months with 31 days: 0?[13578]|1[02]

  • Days maxed at 31: 0?[1-9]|[12]\d|3[01]

  • Days maxed at 28: 0?[1-9]|1\d|2[0-8]

  • Any year from 1000+ (including 2 digit years): [1-9]\d{3}|\d{2}

  • Feb 29: 0?2/29

  • Last two digits of leap years (divisible by 4): [02468][048]|[13579][26]

  • RegexOptions.ECMAScript is important to specify to ensure \d only matches 0-9 digits from English.

  • RegexOptions.ExplicitCapture eliminates the need for non-capturing groups of (?:)

4
  • 1
    I don't know why this was marked down, but it helps in learning the regex--it will take awhile to understand this. :)
    – Alan Wayne
    Commented Aug 4, 2015 at 20:42
  • I can understand the downvote since having a huge regular expression is really convoluted and regex isn't the best tool for the task. However the question did specifically ask for regex and this literally takes care of all corner cases (while still taking all the shortcuts I could think of).
    – Pluto
    Commented Aug 4, 2015 at 20:54
  • Correction to the above comment - @Pluto here has an absolutely elegant original answer. It takes care of recognizing a date pattern embedded in a string even when one has no knowledge of the date format. All one needs to do is remove both \b word boundaries and replace the separators "/" (slash) with "[/- ]?" (slash, dash, space : one or none) so that it can detect dates without any obvious markers. Linked here - regexr.com/57bgg Commented Jun 25, 2020 at 11:57
  • 1
    @ParasParmar Adding onto that, you can ensure the separators are the same by using a named group (since we have explicit capture on) and backreferences. For instance (?<sep>/|-| ) and later on \1 (I haven't tested this but it should work). Forking off of your regular expression, this is demonstrated here: regexr.com/57cnp
    – Pluto
    Commented Jun 26, 2020 at 0:18
4

If you must use regex to validate the format, define the {min,max} in the range quantifier:

^\d{1,2}/\d{1,2}/\d{4}$
3
  • \d{1,2}/\d{1,2}/\d{2,4} allows you to have 2 or 4 digit year. The ^ and $ the are limiting you to only having the date in there line
    – user2046117
    Commented Aug 4, 2015 at 19:00
  • 2
    Note this will match invalid dates like "99/99/0000"
    – juharr
    Commented Aug 4, 2015 at 19:00
  • 2
    @owen79 That'll also allow you to have 3 digit years or match 4 digits of a year when there's a fifth digit after. You'd want /\b\d{1,2}\/\d{1,2}\/(?:\d{2}|\d{4})\b/
    – Pluto
    Commented Aug 4, 2015 at 19:05
0

This will work:

public static class Date_Regex
{
    static string DateRegex = @"\d?[\/|\-|\s]?\d?[\/|\-|\s]\d(\s?)[\/|\-|\s]?\d?(\s?)[\/|\-|\s]\d{4}[\s]?$"; 
    public static string RegexMatches(string content)
    {
        StringBuilder sb = new StringBuilder();
        foreach (Match match in Regex.Matches(content, DateRegex, RegexOptions.Multiline)) 
        {
            sb.Append(match.Value + "; ");
        }
        return sb.ToString();
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.