如何在 VIM 查找/搜索中转义反斜杠和正斜杠?

例如,如果我想用包含向后或向前斜杠的字符串查找和替换,那么在 vim 中如何实现这一点呢?

例子 查找和替换是: :%s/foo/bar/g

如果我想找到 <dog/>的所有出现,并用 <cat\>代替它会怎样

100593 次浏览

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\\>/

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.

%s:<dog/>:<cat>

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

The syntax is:

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

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 /.

backslash slash backslash star

/(<- the prompt)\/\*

so after you type it looks like

/\/\*