Vim Regular Expressions

This page contains some really cool regular expressions for Vim. I'll extend them to future reference.

Search multiple lines

By default, a regex checks line by line. Some suggest to include line wraps \n\r explicitly (but I've not confirmed if that works). Vim supports the construct \_. to match any character including line breaks. The following Regex:

/@incollection\_.\{-}\(\(booktitle\)\|\(crossref\)\)

searches a BIB file for all @incollection entries and highlights up to the following booktitle or crossref. The `{-} ensures a non-greedy behavior, i.o.w. it only goes unto the shortest possible match (see below).

Source

Find the shortest possible match

Commonly, a regex will match as much characters as possible. Not only in multi-line matches (as shown above), but sometimes also in other situations, a non-greedy behavior is wanted.

A simple approach to match the next character is to exclude that from the pattern between:

/<[^>]*>

But if the regex gets more complex, the special multi token \{-} can be used. It will match the shortest possible pattern.

See :help non-greedy and [Source](multi token \{-} can be used. It will match the shortest possible pattern.

See :help non-greedy and Source

Search for lines NOT containing certain words

/@\(\(article\)\@!\&\(inproceedings\)\@!\&.*\){

I've a BibLatex file and want to check all entries, that are not of the classes @article and @inproceedings (all entry types are spelled in lower case, so that I don't have to deal with that).

If the file contains:

01 @article{a,
02    title={Demo article},
03 }
04 @report{b,
05    title={Demo report},
06 }
07 @inproceedings{c,
08    title={Demo presentation},
09 }
10 @misc{d,
11    title={Demo web reference},
12 }

This search pattern would find the lines containing an @ and not article or inproceedings, but something and than an opening curly brace {. This matches the lines 4 and 10.

social