正则表达式,如果某些东西不存在,如何匹配为真?

正则表达式,如果某些东西不存在,如何匹配为真?

I'm fairly decent with regular expressions, but there's one situation that always struggles me, and that is: Give a match when a pattern does not exists in a search string.

Here's a bit of background information:

I use a program called Actual Tools Window Manager, and it allows to create rules based on individual windows. I can either specify the windows title as exact string, or use a regular expression to match.

My goal is to make this rule fire on any window that has a title that does not include a specific string. The regex is only one pattern, similar to the php function: preg_match.

我无法使用捕获组并引用捕获组(至少,我没有让它工作)。

举个例子,假设我想制定一条规则,除了标题中出现 cmd.exe 的情况外,其他所有情况都会触发。

我打开命令提示符,因此它的标题可能是:C:\Windows\System32\cmd.exe我希望根据 cmd.exe 的存在将此窗口排除在我的规则之外

我尝试过类似的方法^cmd.exe,但根本不起作用。

Actual Tools 使用与 Perl 兼容的正则表达式库,因此http://www.pcre.org/无论如何都应该是可能的。

如何才能使正则表达式在某个字符串不存在时匹配成功,而在某个字符串存在时匹配失败?

答案1

这个正则表达式可以完成这个工作:

^(?:(?!cmd\.exe).)*$

解释:

^               : begining of string
  (?:           : start non capture group
    (?!         : start negative lookahead
      cmd\.exe  : literally (you may add wordboundaries \bcmd\.exe\b if you don't want to match mycmd.exe)
    )           : end lookahead
    .           : 1 any character but newline
  )*            : end group, repeated 0 or more times
$               end of string

例子:

C:\Windows\System32\cmd.exe         --> Doesn't match
C:\Windows\System32\mycmd.exe       --> Doesn't match without wordboundaries, else Match
C:\Windows\System32\cmd             --> Match
C:\Windows\System32\exe             --> Match

相关内容