Skip to content

Instantly share code, notes, and snippets.

@dreftymac
Last active March 15, 2017 13:33
Show Gist options
  • Save dreftymac/25fe42810f5d930bb87677b133af5d08 to your computer and use it in GitHub Desktop.
Save dreftymac/25fe42810f5d930bb87677b133af5d08 to your computer and use it in GitHub Desktop.
vim regular expressions for perl regex fans

Overview

Vim regular expressions are powerful, but they pre-date Perl.

This can be frustrating since the Perl-flavored-regex syntax has expanded beyond into other programming languages and contexts, becoming a de-facto standard.

This guide is a quick cheatsheet and tipsheet for using regular expressions in Vim for those who may be more familiar with Perl.

Quick examples for vimmers who like Perl regex

Here are some quick general-purpose examples.

Whitespace, empty line, newline

/                       ;; <space> (ASCII \x20 space character)
/\s                     ;; <whitespace> (includes tab and any other space char)
/\s\+                   ;; one or more <whitespace>
/\S\+                   ;; one or more <non-whitespace>
/^$                     ;; empty line

Character class

/\_.                    ;; any character (including newline)
/[a-z]\| /              ;; ( (a thru z) or <space> )
/[0-9]\|\s/             ;; ( (0 thru 9) or <whitespace> )
/\w\W\|\W\w/            ;; ( (word/nonword) or (nonword/word) )
/\w\W\|\W\w\|\s\S/      ;; word/nonword or nonword/word
/caption/e+2            ;; end of pattern match, plus two chars after

Quick examples without "leaning toothpick syndrome"

To make Vim regex a little more like Perl regex, the \v flag can be used.

It may not do much to reduce keystrokes, but it can help mitigate "leaning toothpick syndrome".

/\v\s+                  ;; one or more <whitespace>
/\v\w+                  ;; one or more <wordchar>
/\v[0-9]|\s             ;; ( (0 thru 9) or <whitespace> )  
/\v\k+\s+=              ;; one or more <keywordchar> then <whitespace> then equalsign

See also

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment