Skip to main content
 首页 » 编程设计

C# 正则表达式不包括一个字符 (!)

2024年01月31日28www_RR

下面的正则表达式运行良好:

\bG1\b 

但我想修改它以在前面带有 ! 的情况下不查找 G1 事件。例如:

='Plan1'!G1            --> NOT match! 
=G1*G2                 --> MATCH! 
='Plan2'!A1+'Plan2'!G1 --> NOT match! 

这个正则表达式怎么会?

请您参考如下方法:

你需要一个 negative lookbehind :

(?<!subexpression)
where subexpression is any regular expression pattern. For a match to be successful, subexpression must not occur at the input string to the left of the current position. However, any substring that does not match subexpression is not included in the match result.

所以,使用

(?<!!)\bG1\b 
^^^^^^ 

参见 regex demo