2014-04-29 46 views
0

我有一個字符串01-Jan-2014 00:00:00,我打算將年份縮短爲2個字符。Regex.Replace和String.Replace不起作用

我的代碼:

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")); 

我驗證過的字符串使用正則表達式正確匹配。

「01-Jan-2014」未被替換爲「01-Jan-14」。我的代碼有什麼問題?

+2

[閱讀文檔(http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(V = vs.110)的.aspx)。 'Regex.Replace'返回一個新的字符串,它不會改變你傳入的字符串(因爲字符串是不可變的)。 –

回答

2

Regex.ReplaceString.Replace不修改現有字符串:它們返回修改過的字符串。試着改變你的代碼:

arrData[iCol] = regDate.Replace(arrData[iCol], dtParsedDate.ToString("dd-MMM-yy")); 
2

在.NET中,字符串是不可變的,所有的替換方法都不會在原來的位置替換,而是返回一個替換完成的新字符串。