日期:2014-05-17  浏览次数:20835 次

求写个关于日期的正则表达式
我一个数据表有一个字段是
这样子的


我现在想把这个字段格式化成
2013-01-26这种类型


-------------------------------------
有些字段没写年份的,自动归类为今年;
有些字段没写哪一天的,就自定写当月的1号,比如2012年4月或者4月,就格式化成2012-04-01;
而"11年10月1日推出1号楼"则格式化成2011-10-1

------解决方案--------------------
void Main()
{
    var test=new string[]{"预计2013年12月31日","11年10月1日推出1号楼","一期一批次2013-12-31","2012-12","2014年12月","11年12月","2014年12月31日","8月9号"};
Regex reg=new  Regex(@"((?<y>\d{2,4})[年-])?(?<m>\d{1,2})([月-]
------解决方案--------------------
$)((?<d>\d{1,2})([日号]
------解决方案--------------------
$))?");
Regex r=new Regex("[^\\d-]");
foreach(var s in test)
{
  if(reg.IsMatch(s))
  { 
        Match m=reg.Match(s);  
string year=!m.Groups["y"].Success?DateTime.Now.Year.ToString():m.Groups["y"].Value.Length==2?"20"+m.Groups["y"].Value:m.Groups["y"].Value;
string month=!m.Groups["m"].Success?"1":m.Groups["m"].Value;
string day=!m.Groups["d"].Success?"1":m.Groups["d"].Value;
string result=string.Format("{0}-{1}-{2}",year,month,day); 
Console.WriteLine("{0}\t\t{1}",s,result);
  }
}
}