1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text.RegularExpressions; 5 public class Program 6 { 7 public static void Main() 8 { 9 var reg = @"^(?:\d{4}/(?:(?:0?[1-9]|1[0-2])/(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])/(?:29|30)|(?:0?[13578]|1[02])/31)|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)/0?2/29)$"; 10 11 var reg2 = @"^(?:\d{4}(?:(?:0?[1-9]|1[0-2])(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])(?:29|30)|(?:0?[13578]|1[02])31)|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)0?229)$"; 12 13 var str = "2034/05/05"; 14 15 var match = Regex.IsMatch(str, reg); 16 Console.WriteLine(match); 17 str = "20340505"; 18 str = "203019"; 19 match = Regex.IsMatch(str, reg2); 20 Console.WriteLine(match); 21 22 DateTime dtWork; 23 var date = "203012"; 24 25 if ( DateTime.TryParseExact(date, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out dtWork)) 26 { 27 Console.WriteLine(dtWork); 28 } 29 else 30 { 31 Console.WriteLine(dtWork); 32 } 33 34 str = "110111"; 35 var reg3 = @"^(?:(?:(?:(?:(?:1[6-9]|[2-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:0229))|(?:(?:(?:1[6-9]|[2-9]\d)\d{2})(?:(?:(?:0[13578]|1[02])31)|(?:(?:0[13-9]|1[0-2])(?:29|30))|(?:(?:0[1-9])|(?:1[0-2]))(?:0[1-9]|1\d|2[0-8]))))$"; 36 Console.WriteLine(Regex.IsMatch(str, reg3)); 37 38 str = "20190228"; 39 var reg4 = @""; 40 Console.WriteLine(Regex.IsMatch(str, reg4)); 41 42 } 43 }
输出:
True
True
01/01/0001 00:00:00
False
True