Reputation: 333
I would like to combine two regular expressions. The first one is a negative lookahead:
^(.(?!(test)))*$
It matches my data that does not contain "test".
Now I would like to combine it with a basic search: I would like to find data that does not contain "test" (string 1) but does contain "fix" (string 2). How can I combine these two into a single regular expression?
For my purpose it doesn't matter where these strings appear, as long as "test" does not appear and "fix" does appear.
Upvotes: 2
Views: 2749
Reputation:
Either of these ways will work:
Type 1
# ^(?!.*test)(?=.*fix).*$
^
(?! .* test )
(?= .* fix )
.*
$
Type 2
# ^(?:(?!test).)*fix(?:(?!test).)*$
^
(?:
(?! test )
.
)*
fix
(?:
(?! test )
.
)*
$
Upvotes: 1
Reputation: 5515
^(?!.*test)(?=.*fix)(.*)$
is a general solution for this. it doesn't really matter what order the lookarounds are in since the regex cursor will not move until the lookarounds have been parsed.
the only thing I want to say about this, and I made it this way because thats what your regex is like, is that if there are words like fixed
or tested
, those will be caught by the look aheads. you can change this by adding word boundaries
^(?!.*\btest\b)(?=.*\bfix\b)(.*)$
EDIT: if you want to match across multiple lines, take out /m and replace with /s or change .
token
^(?![\s\S]*test)(?=[\s\S]*fix)([\s\S]*)$
Upvotes: 5