.net Regex.Replace和String.Replace不起作用
我有一个字符串.net Regex.Replace和String.Replace不起作用,.net,regex,.net,Regex,我有一个字符串01-Jan-2014 00:00:00,我打算将年份缩短为2个字符 我的代码: DateTime dtParsedDate = new DateTime(); string strInput = "01-Jan-2014 00:00:00"; Regex regDate = new Regex(@"\d{2}-\w{3}-\d{4}"); // parse into datetime object dtParsedDate = DateTime.ParseExact(regDa
01-Jan-2014 00:00:00
,我打算将年份缩短为2个字符
我的代码:
DateTime dtParsedDate = new DateTime();
string strInput = "01-Jan-2014 00:00:00";
Regex regDate = new Regex(@"\d{2}-\w{3}-\d{4}");
// parse into datetime object
dtParsedDate = DateTime.ParseExact(regDate.Match(strInput).Value, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
// replace the string with new format
regDate.Replace(arrData[iCol], dtParsedDate.ToString("dd-MMM-yy"));
我已经使用正则表达式验证了字符串是否正确匹配
“2014年1月1日”未替换为“2014年1月1日”。我的代码有什么问题?在.NET字符串中是不可变的,所有替换方法都不原地替换,而是在替换完成后返回一个新字符串。在.NET字符串中是不可变的,所有替换方法都不原地替换,而是在替换完成后返回一个新字符串。
Regex.replace
和String.Replace
不修改现有字符串:它们返回修改后的字符串。尝试将代码更改为:
arrData[iCol] = regDate.Replace(arrData[iCol], dtParsedDate.ToString("dd-MMM-yy"));
Regex.Replace
和String.Replace
不修改现有字符串:它们返回修改后的字符串。尝试将代码更改为:
arrData[iCol] = regDate.Replace(arrData[iCol], dtParsedDate.ToString("dd-MMM-yy"));
. Regex.Replace
返回一个新字符串,它不会改变传递给它的字符串(因为字符串是不可变的)Regex.Replace
返回一个新字符串,它不会改变传递给它的字符串(因为字符串是不可变的)。