您的代码看起来不错,但请记住,当您像这样进行不区分大小写的匹配时,您使用的是当前的语言环境或文化。最好添加您想要的文化,或者让用户选择它。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);
最后一个很有趣:在(?:)
非捕获分组括号之后,case-switch(?-i)
不再有效。您可以在表达式中随意使用它。在不分组的情况下使用它可以使它们在下一次区分大小写切换之前有效,或者到最后。
更新:我做出了错误的假设,即您不能进行区分大小写的切换。上面的文字是在考虑到这一点的情况下编辑的。