您的代碼似乎沒問題,但請記住,當您進行不區分大小寫的匹配時,請使用當前的語言環境或文化。最好添加你想要的文化,或讓用戶選擇它。 CultureInvariant
通常是採取行動的同在任何語言環境的好一般選擇:
Regex.Replace(textBoxText,
Regex.Escape(findText),
replaceText,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
要使用其他語言環境,你需要做的多一點騙人把戲:
// remember current
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
// set user-selected culture here (in place of "en-US")
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// do the regex
Regex.Replace(textBoxText,
Regex.Escape(findText),
replaceText,
RegexOptions.IgnoreCase);
// reset the original culture
Thread.CurrentThread.CurrentCulture = originalCulture;
請注意,您可以切換的情況下不敏感開啓或關閉。它不是一個切換,這意味着:
// these three statements are equivalent and yield the same results:
Regex.Replace("tExT", "[a-z]", "", RegexOptions.IgnoreCase);
Regex.Replace("tExT", "(?i)[a-z]", "", RegexOptions.IgnoreCase);
Regex.Replace("tExT", "(?i)[a-z]", "");
// once IgnoreCase is used, this switches it off for the whole expression...
Regex.Replace("tExT", "(?-i)[a-z]", "", RegexOptions.IgnoreCase);
//...and this can switch it off for only a part of the expression:
Regex.Replace("tExT", "(?:(?-i)[a-z])", "", RegexOptions.IgnoreCase);
最後一個是有趣:非捕獲分組括號後的(?:)
之間的情況下,開關(?-i)
無效了。你可以在表達式中儘可能多地使用它。無需分組就可以使用它,直到下一個區分大小寫切換或結束時纔有效。
更新:我做了錯誤的假設,你不能做區分大小寫切換。上面的文字是根據這個編輯的。
我同意這不是重複。 – 2009-12-03 14:31:58