Changing regex delimiters
Pattern matching and substitution with regular expressions is a commonly used Vim feature. We’ve written a lot about substitution and pattern matching in the past.
Typically, when performing a substitution, you would use the :s
command followed by a regular expression that’s delimited by slashes /
and followed by any flags, such as g
to replace all occurrences on the line. For example:
:s/foo/bar/g
But did you know that the regular expression delimiter can be anything and is not limited to /
? This command is equivalent:
:s#foo#bar#g
Whatever character you use after the s
is considered the delimiter. You can use almost any character except \
, "
, or |
. Why would you care to use a different delimiter? Because then you don’t need to escape the slash.. For example, replacing a file path: Instead of:
:/\/User\/local\/bin\//\/usr\/sbin\//g
You can use #
as your delimiter and skip escaping the /
which makes for something far easier to parse:
:#/User/local/bin/#/usr/sbin/#g