0

I wanna create a generic DateTime regular expression that will match all possible C# DateTime formats like the TryParse of Microsoft.

MM/dd/Year
dd/MM/Year
dd/MM/YY
MM/dd/YY
dd/MM/Year hh:mm
...

Have you any suggestion ? If it will be simple I could also separate the Date from the Time. and create a regular expression for Date and one for Time.

stema
  • 90,351
  • 20
  • 107
  • 135
Claudio Ferraro
  • 4,551
  • 6
  • 43
  • 78
  • And how would you handle the ambiguity with the date 12/12/12? Is that MM/dd/YY? YY/MM/dd? dd/MM/YY? – Jim Mischel Nov 28 '11 at 15:42
  • I wanna just handle the isMatch or not. Doesn't really matter if the Month was first or not..It's a general check that will determine if mainly the provided value is a C# date or not. Doesn't really matter if it's american or chinese format. I wanna simply to avoid that the system will match a string like: YOU ARE STUPID – Claudio Ferraro Nov 28 '11 at 16:43

1 Answers1

5

No, you don't want to do that. You would have to deal with number ranges and that is not what regexes are created for. Not to talk about the different amount of days per month and leap years. (See for example here and this solution does not take care about leap years and is only for one Pattern.)

Whats wrong with the DateTime.Parse Method (String)?

You can do something like

string t = "01/01/1899";
DateTime Date = DateTime.Parse(t);

and it will raise a FormatException if t is not a valid DateTime format.

Update: Finding a pattern in text

OK, to find a Date/Time pattern in a Text, without verifying it, you can try something like this:

\b\d{1,2}/\d{1,2}/\d{2,4}(?:\s+\d{1,2}:\d{1,2})?\b

You can see and test it by yourself here on Regexr

Short introduction:

\b is a word boundary, it ensures that before the first and after the last digit is neither another digit nor a letter.

\d is a digit. \d{1,2} are one or two digits.

\s is a whitespace. \s+ is one or more whitespace.

(?: ... )? is a non capturing group and because of the ? at the end this group (here the pattern for the time) is optional.

I think that should be mainly all you need to create your pattern to find all the Date/Time formats you want.

Community
  • 1
  • 1
stema
  • 90,351
  • 20
  • 107
  • 135
  • nothing is wrong with the parse method..but I should handle a situation in which the date resides in a bigger string and the place is unknown. I wanna a regular expression which matches all types of possible dates ..I don't wanna to check if the value matches perfectly. – Claudio Ferraro Nov 28 '11 at 20:19
  • @ClaudioFerraro I added a solution to find patterns in text. – stema Nov 28 '11 at 21:51