我正在研究一个正则表达式,它可以匹配一个词的所有实例,但包含该词的特定字符串除外。
例如,我想匹配 stack
的所有实例 在下面的句子中除了 stack.overflow
(因为后面跟着 .overflow
)并替换 stack
与 STACK
This is a stack of pages on stack overflow. Sometimes also referred to as stack.overflow.com
执行替换操作后,上面的句子应该是这样的:
This is a STACK of pages on STACK overflow. Sometimes also referred to as stack.overflow.com
编辑:
为了澄清一些混淆,我想匹配所有包含 stack
的字符串除特殊情况外全部小写 stack
其次是.overflow
.比如下面这句话
I stacked this stacking stack and re-stacked (stACked it again) but no stack.overflow but stacked.overflow and restacked.overflow
应该是
I STACKed this STACKing STACK and re-STACKed (stACked it again) but no stack.overflow but STACKed.overflow and reSTACKed.overflow
最佳答案
使用否定前瞻。
\bstack(?!\.overflow)
要使其不区分大小写,请使用 RegexOptions.IgnoreCase
标志。
带有 Regex.Replace
的 C# 示例代码,其中标志被替换为内联 (?i)
选项:
var res = Regex.Replace(input, @"(?i)\bstack(?!\.overflow)", "STACK");
证明:
关于c# - 正则表达式,用于匹配一个单词的所有实例,但包含该单词的特定超字符串除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29959595/