开发者

Regular expression for dd/mm

开发者 https://www.devze.com 2023-01-01 06:09 出处:网络
Please help me with a regular expressi开发者_JAVA技巧on to validate the following format dd/mm This is for validating a Birthday field and the year is not required.

Please help me with a regular expressi开发者_JAVA技巧on to validate the following format

dd/mm

This is for validating a Birthday field and the year is not required.

Thanks


bool foundMatch = false;
foundMatch = Regex.IsMatch(SubjectString, 
    @"^(?:
     (?:[12][0-9]|0?[1-9])/(?:0?2|Feb(?:ruary)?)
     |
     (?:30|[12][0-9]|0?[1-9])/
      (?:
       (?:0?[469]|11)
       |
       Apr(?:il)?|June?|Sep(?:tember)?|Nov(?:ember)?
      )
     |
     (?:3[01]|[12][0-9]|0?[1-9])/
      (?:
       (?:0?[13578]|1[02])
       |
       Jan(?:uary)?|Mar(?:ch)?|May|July?|Aug(?:ust)?|Oct(?:ober)?|Dec(?:ember)?
      )
     )$",  
    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

will match valid days/months. It will always match Feb 29 since it doesn't know the year.

By the way, I made this regex using RegexMagic (much too tedious to do this manually - another sign that this is rather a job for a date/time parser).


^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])$

but this one will allow for example 30/02


new Regex(@"^\d{2}/\d{2}$")

or:

new Regex(@"^\d\d/\d\d$")

\d represents a digit, and {2} specifies that it must be repeated twice.

To check if it's a real date, use DateTime.TryParseExact:

DateTime date;
bool valid;
valid = DateTime.TryParseExact("00/00", "dd/MM", null, DateTimeStyles.None, out date); // false
valid = DateTime.TryParseExact("30/02", "dd/MM", null, DateTimeStyles.None, out date); // false
valid = DateTime.TryParseExact("27/02", "dd/MM", null, DateTimeStyles.None, out date); // true

However, this will not handle leap years properly. Probably the best solution is to ask for the year of birth after all.

0

精彩评论

暂无评论...
验证码 换一张
取 消