如何为特定日期格式创建正则表达式 [英] how to create a regular expression for perticular date format

查看:89
本文介绍了如何为特定日期格式创建正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想为日期格式创建一个正则表达式



21 2014年4月



我尝试了一些正则表达式,但没有得到任何解决方案。





(((((([(1-9))|( 0  [1-9])|( [0-1] [0-2])))[\] { 1 } 
([AZ] { 1 } \ b)([az] { 2 })[\] { 1 }
(([1-9])|([1-2] [0-9])|( 30 )) )|( 2 [\ /] { 1 }(([1-9])|( [1-2] [0-9]))))[\ /] { 1 } \d { 4 })

解决方案

如果要验证日期,正则表达式不能。

您应该使用 DateTime.TryParseExact方法 [ ^ ]

查看我的示例:

 使用系统; 
使用 System.Globalization;

public class 计划
{
public static void Main()
{
string dateString = 2014年4月21日; // < - 有效
string format = dd MMM yyyy;
DateTime dateTime;
if (DateTime.TryParseExact(dateString,format,CultureInfo.InvariantCulture,DateTimeStyles.None, out dateTime))
{
Console.WriteLine( 这是一个有效的日期);
}
else
{
Console.WriteLine( 它不是有效日期);
}
}
}


试试这个:



^(((((0 [1-9])|(1 \d)|(2 [0-8])) - ((0 [1-9])|(1 [0-2] )))|((31 - ((0 [13578])|(1 [02])))|((29 | 30) - ((0 [1,3-9])|(1 [0-2 ]))))) - ((20 [0-9] [0-9]))|(29-02-20(([02468] [048])|([13579] [26]))))


Hi,

I want to create a regular Expression for following for date format

21 Apr 2014

I Have tried some regular expressions but did not get any solution.


(((((([1-9])|(0[1-9])|([0-1][0-2])))[\ ]{1}
([A-Z]{1}\b)([a-z]{2})[\ ]{1}
(([1-9])|([1-2][0-9])|(30)))|(2[\/]{1}(([1-9])|([1-2][0-9]))))[\/]{1}\d{4})

解决方案

If you want to validate a date, regular expression can't.
You should use DateTime.TryParseExact Method[^]
See my example:

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        string dateString = "21 Apr 2014"; // <-- Valid
        string format = "dd MMM yyyy";
        DateTime dateTime;
        if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,  DateTimeStyles.None, out dateTime))
        {
            Console.WriteLine("It is a valid date");
        }
        else
        {
            Console.WriteLine("It is NOT a valid date");
        }
    }
}


Try This:

^(((((0[1-9])|(1\d)|(2[0-8]))-((0[1-9])|(1[0-2])))|((31-((0[13578])|(1[02])))|((29|30)-((0[1,3-9])|(1[0-2])))))-((20[0-9][0-9]))|(29-02-20(([02468][048])|([13579][26]))))



这篇关于如何为特定日期格式创建正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆