Changing regex delimiters

3.6
(468)

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

How useful was this tip?

Average rating 3.6 / 5. Vote count: 468

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts