日期:2014-5-18 浏览次数:20238次

替换文本中的时间
比如文本中的内容如下:
1 2012 11 28 hhhhhhhbni fdfsasdfsdfsa
dfoisafio jsdpofpjas sodjf 
dnfinspaffsa
dnsfpasfa'fad[fa
2 2012 11 29 jpdsjofjs[a[k[paskf[a f
dfjopas fa [sdfk[pa [as[fk
dpfoapfsdo[f
;osafo
3 2012 11 27 dpofjap poasojfpajsa
ndfa'opfd
fpaspfj pa'f
pas'fj'afj'afj'afj'af
4 2012 9 28 posdjf]opa'pfasjp'fas[a
;asfjp'asjdj'fas
n;kslanfl;a
;safn;a'a;ldfj;'a
我想把2012 11 28替换成2011 9 11,相对的2012 11 29就替换成2011 9 12,2012 11 27替换成2011 9 10号。请问有什么好办法可以解决?

------解决方案--------------------
C# code

TimeSpan ts = new DateTime(2011, 9, 11) - new DateTime(2012, 11, 28);
string 结果 = new Regex(@"20\d{2} \d{1,2} \d{1,2}").Replace(原字符串, new MatchEvaluator((o) =>
{
    return (Convert.ToDateTime(o.Value) + ts).ToString("yyyy M d");
}));

------解决方案--------------------
C# code

 string input = @"
1 2012 11 28 hhhhhhhbni fdfsasdfsdfsa
dfoisafio jsdpofpjas sodjf 
dnfinspaffsa
dnsfpasfa'fad[fa
2 2012 11 29 jpdsjofjs[a[k[paskf[a f
dfjopas fa [sdfk[pa [as[fk
dpfoapfsdo[f
;osafo
3 2012 11 27 dpofjap poasojfpajsa
ndfa'opfd
fpaspfj pa'f
pas'fj'afj'afj'afj'af
4 2012 9 28 posdjf]opa'pfasjp'fas[a
;asfjp'asjdj'fas
n;kslanfl;a
;safn;a'a;ldfj;'a
";
            int k= 0;
            string[] newstr = new string[] { "2011 9 11", "2011 9 12", "2011 9 10" };
            string pat = @"(?i)\d{4}\s*\d{2}\s*\d{2}";
            
            input = Regex.Replace(input, pat, new MatchEvaluator(d =>
            {
                k++;
                return d.Value == "" ? "" : newstr[k-1];
            }));
/*
1 2011 9 11 hhhhhhhbni fdfsasdfsdfsa
dfoisafio jsdpofpjas sodjf 
dnfinspaffsa
dnsfpasfa'fad[fa
2 2011 9 12 jpdsjofjs[a[k[paskf[a f
dfjopas fa [sdfk[pa [as[fk
dpfoapfsdo[f
;osafo
3 2011 9 10 dpofjap poasojfpajsa
ndfa'opfd
fpaspfj pa'f
pas'fj'afj'afj'afj'af
4 2012 9 28 posdjf]opa'pfasjp'fas[a
;asfjp'asjdj'fas
n;kslanfl;a
;safn;a'a;ldfj;'a
*/