Searching for expressions which include slashes

This tip explains how to search for a path of the form /abc/def/ghi/ without needing to manually escape each slash (using the normal / command would require the example path to be entered as \/abc\/def\/ghi\/). In addition, a command is shown to allow searching for text while treating all special search characters as just text (so you can easily search for text like a*b or ^ab without needing to enter a\*b or \^ab).

Contents

If searching backwards with "?", any slashes in the pattern need not be escaped. After searching backwards, you can press n to continue searching in the same direction (backwards), or N to search in the reverse direction (forwards). Or, you can search forwards with / and no pattern, which will use the previous pattern:

?/abc/def/ghi/
/

Now, pressing n will search forwards for the next occurrence, and N will search backwards.

The following alternative commands allow searching for text which includes a slash, with no need to escape each slash in the command. Other special characters have their usual meaning (for example, the pattern ^abc finds abc, but only at the start of a line).

In the last example, <C-R>/ represents Ctrl-R then / which enters the value of the search register into the search command (the first /). The escape() function is required to prefix any slashes with a backslash because the text is used in a / command (where a search pattern is terminated by an unescaped slash). Since the command performs an actual search, the pattern is placed in the search history.

The :substitute command accepts any punctuation character to delimit the search pattern, not just /. For example, assuming the path being searched for does not contain a comma, the following command could be entered:

:s,/abc/def/ghi/,,en

The e flag means no error is reported if the pattern is not found in the current line, and n means the pattern is counten with no change occurring. After entering the command, press n to search forwards or N to search backwards.