How does one escape backslashes and forward slashes in VIM find/search?

RegexVim

Regex Problem Overview


For instance, if I wanted to a find and replace with strings containing backward or forward slashes, how would this be accomplished in vim? Thank you!

Examples Find & Replace is: :%s/foo/bar/g

what if I wanted to find all occurrences of <dog/> and replace it with <cat\>

Regex Solutions


Solution 1 - Regex

Same way you escape characters most anywhere else in linuxy programs, with a backslash:

:%s/<dog\/>/<cat\\>

But note that you can select a different delimiter instead:

:%s@<doc/>@<cat\\>@

This saves you all typing all those time-consuming, confusing backslashes in patterns with a ton of slashes.

From the documentation:

>Instead of the / which surrounds the pattern and replacement string, you can use any other single-byte character, but not an alphanumeric character, \, " or |. This is useful if you want to include a / in the search pattern or replacement string.

Solution 2 - Regex

%s:<dog/>:<cat>

You can replace the / delimiters if they become annoying for certain patterns.

Solution 3 - Regex

Quote them with a backslash. Also, it often helps to use another delimiter besides slash.

 :%s#<dog/>#<cat\\>#

or if you have to use slash as the substitute command delimiter

 :%s/<dog\/>/<cat\\>/

Solution 4 - Regex

I was looking for something similar, to search for register values containing the / character (to record a macro). The solution was to search using the ? token instead of the /.

Solution 5 - Regex

The syntax is:

:%s/<dog\/>/<cat\\>/g

Solution 6 - Regex

backslash slash backslash star

/(<- the prompt)\/\*

so after you type it looks like

/\/\*

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstormistView Question on Stackoverflow
Solution 1 - RegexCascabelView Answer on Stackoverflow
Solution 2 - RegexSarahView Answer on Stackoverflow
Solution 3 - RegexwallykView Answer on Stackoverflow
Solution 4 - RegexFernandoView Answer on Stackoverflow
Solution 5 - RegexMaurizio ReginelliView Answer on Stackoverflow
Solution 6 - Regexjim kView Answer on Stackoverflow