Suppose I have a file with lines that contain the following strings:
...cat dog lorem ipsum...
...cat lizard ...
...cat bird ...
...cat dog ...
I want to write a regex that matches the lines in which cat
is not followed by dog
:
...cat lizard ...
...cat bird ...
How can I do this?
In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.
In order to match a line that does not contain something, use negative lookahead (described in Recipe 2.16). Notice that in this regular expression, a negative lookahead and a dot are repeated together using a noncapturing group.
Regular expressions are useful in search and replace operations. The typical use case is to look for a sub-string that matches a pattern and replace it with something else. Most APIs using regular expressions allow you to reference capture groups from the search pattern in the replacement string.
Inversely match an atom by following it with @!
. In this case, the atom we want to not-match is a capture group matching the string dog
:
/\vcat (dog)@!
Broken down:
\v
activates very magic parsing mode(dog)
matches the string dog
and puts it in capture group 1@!
inverts the atom (dog)
, so that the pattern matches when dog
is absent
This matches instances of cat
(and a trailing space) not followed by dog
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With