Paige
Paige

Reputation: 685

Vim negative lookahead and negative look behind in one regular expression

I am trying to convert this regular expressions from sublime text into one I can use in vim: (?<![>\w\d])(42|45|21)\s(?!days)

I would like to match 42, 45, and 21 where they are not immediately proceeded by a <, a word character, or a digit and are not followed by the word days.

In example, I want to find the 42 in this: This is a reference to chapter 42 in the book.

But not this: This is a reference to chapter <a href="#">42</a>.

Or this: This is a reference to chapter <a href="#">42 section 35</a>.

Or this: This book took 42 days to write.

I am fairly new to regular expressions in general and super new to vim, so please forgive me if this is a malformed regex to begin with.

Upvotes: 11

Views: 3362

Answers (1)

rbernabe
rbernabe

Reputation: 1072

Got it

\([>]\)\@<!\<\(4[25]\|21\)\( days\)\@!

or

\v([>])@<!<(4[25]|21)( days)@!

As you can see, syntax for lookaround is different in vim and you have more than one mode for searching with regular expressions I generally use nomagic and very magic

Take some time to see the help of magic modes: :help /magic

EDIT

Now it includes 45 and 21 too

Upvotes: 18

Related Questions