您的代码似乎没问题,但请记住,当您进行不区分大小写的匹配时,请使用当前的语言环境或文化。最好添加你想要的文化,或让用户选择它。 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