c# - Regex.Replace 无法按预期使用 Regexoptions.IgnoreCase

标签 c# .net regex

如果我有几个字符串:

str = "This is a cool string (orch. details here): 2. Denied."
str2 = " (Orch. details here)" <--notice the capital letter

然后我执行这行代码以尝试清除该部分:

str3 = Regex.Replace(str, str2, "", RegexOptions.IgnoreCase);

str3 最终与执行前的 str 完全相同。我怀疑它没有“看到”其他字符,例如句点,因为当我只使用 strstr2 中的简单字母字符执行此操作时,它将仅替换它很好。

什么给了?! :)

感谢您的任何见解!

最佳答案

括号和句点在正则表达式中都有含义。因此,它不是试图逐字匹配 str2 的内容,而是尝试匹配 str2 定义的正则表达式。如果你想让它按字面意思匹配,你需要转义字符串

str2 = Regex.Escape(str2);

关于c# - Regex.Replace 无法按预期使用 Regexoptions.IgnoreCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20974333/

相关文章:

regex - Perl 和 Mechanize : can't get multiple matches for my simple regex

html - 正则表达式禁止 HTML 标签?

c# - 解析字符串 C#(可能使用正则表达式)

C# 调用 MySQL 存储过程、函数的最佳方式

c# - 为什么中间件组件在 .Net Core 管道中被调用两次?

.NET 垃圾收集延迟

c# - 如何显示任务栏通知?

python - 在 Python 中以特定模式打印字母

c# - autofac 中的条件组件注册

c# - 如何迭代静态类中的所有静态公共(public)Guid