我需要一个正则表达式来支持日期格式 dd-MMM-yyyy
和 dd-MMM
。
例如:
04-Oct-2010
04-Oct
04-OCT-2010
04-OCT
最佳答案
如果您只需要 C# 解决方案,还有更优雅的解决方案:
//I intentionally change to 5th of October
var stringDates = new string[] { "05-Oct-2010", "05-Oct", "05-OCT-2010", "05-OCT" };
foreach(var s in stringDates)
{
DateTime dt;
if (DateTime.TryParseExact(s, new string[] { "dd-MMM-yyyy", "dd-MMM" }, null, DateTimeStyles.None, out dt) )
Console.WriteLine(dt.ToShortDateString());
}
此代码打印:
05/10/2010
05/10/2010
05/10/2010
05/10/2010
您甚至可以使用一些奇特的 LINQ:
static DateTime? Parse(string str, string[] patterns)
{
DateTime result;
if (DateTime.TryParseExact(str, patterns, null, DateTimeStyles.None, out result) )
return result;
return null;
}
static void Main(string[] args)
{
var stringDates = new string[] { "05-Oct-2010", "05-Oct", "05-OCT-2010", "05-OCT" };
var patterns = new string[] {"dd-MMM-yyyy", "dd-MMM"};
var dates = from s in stringDates
let dt = Parse(s, patterns)
where dt.HasValue
select dt.Value;
foreach( var d in dates)
Console.WriteLine(d.ToShortDateString());
Console.ReadLine();
}
我们得到了相同的结果;)
关于c# - dd-MMM-yyyy 和 dd-MMM 的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3858413/