日期正则表达式

 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 }
View Code

输出: 

True
True
01/01/0001 00:00:00
False
True

转载于:https://www.cnblogs.com/RocCnBlog/p/11240831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>