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.
I cannot work with capture groups and refer to a capture group (at least, I didn't get that to work).
As an example, lets say I want to make a rule that fires on everything except when cmd.exe is in the title.
I open a Command prompt so its likely the title will have: C:\Windows\System32\cmd.exe I want this window be excluded from my rule based om the presence of cmd.exe
I tried things like ^cmd.exe but that simply doesn't work.
Actual Tools uses a Perl Compatible Regular Expression library, so should all be possible somehow.
How can I make a regex that matches OK if a certain string is not present, but FAIL if that string is present?
1 Answer
This regex does the job:
^(?:(?!cmd\.exe).)*$Explanation:
^ : 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 stringExamples:
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 0