Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a pattern not followed by a sub-pattern in Vim [duplicate]

Tags:

regex

vim

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?

like image 684
Stew Avatar asked Dec 31 '15 16:12

Stew


People also ask

How do I match a pattern in Vim?

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.

How do you say does not contain in regex?

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.

Why use regex?

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.


1 Answers

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:

  1. \v activates very magic parsing mode
  2. (dog) matches the string dog and puts it in capture group 1
  3. @! 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.

like image 116
Stew Avatar answered Oct 02 '22 13:10

Stew