Reputation: 4721
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.
Upvotes: 0
Views: 1829
Reputation: 93086
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.
Upvotes: 5