vim中的精确字符串匹配?(比较少的'regex-off'模式.)

jog*_*ran 35 vim search escaping

vim中,我经常想要搜索带有需要转义的挑剔字符的字符串.有没有办法可以关闭所有特殊字符的含义,有点像regex-off模式在less或fgrep中

我正在处理特别毛茸茸的弦; 这是一个例子:

((N/N)/(N/N))/N
Run Code Online (Sandbox Code Playgroud)

不必逃避任何角色在vim中进行搜索将是一个重要的节省时间.

\ V in Vim有助于一些元字符,但严重不是/或\.


谢谢大家!最后,我将此添加到我的.vimrc:

command! -nargs=1 S let @/ = escape('<args>', '\')
nmap <Leader>S :execute(":S " . input('Regex-off: /'))<CR>
Run Code Online (Sandbox Code Playgroud)

Mar*_*off 31

根据您正在搜索的确切字符串,\V前缀可能会起作用.
:help \V:

after:    \v       \m       \M       \V         matches ~
                'magic' 'nomagic'    
          $        $        $        \$         matches end-of-line
          .        .        \.       \.         matches any character
          *        *        \*       \*         any number of the previous atom
          ()       \(\)     \(\)     \(\)       grouping into an atom
          |        \|       \|       \|         separating alternatives
          \a       \a       \a       \a         alphabetic character
          \\       \\       \\       \\         literal backslash
          \.       \.       .        .          literal dot
          \{       {        {        {          literal '{'
          a        a        a        a          literal 'a'
Run Code Online (Sandbox Code Playgroud)

因此,如果我有一个字符串hello.*$world,我可以使用该命令/\V.*$来查找.*$- 需要转义的字符串的唯一部分是另一个反斜杠,但您仍然可以通过转义特殊符号来进行分组等.


您可以用来"避免"正斜杠的另一个命令是:

:g #\V((N/N)/(N/N))/N#   
Run Code Online (Sandbox Code Playgroud)

:g命令是全局搜索,注意到:

:[range]g[lobal]/{pattern}/[cmd]
                        Execute the Ex command [cmd] (default ":p") on the
                        lines within [range] where {pattern} matches.

Instead of the '/' which surrounds the {pattern}, 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.
Run Code Online (Sandbox Code Playgroud)

所以,在这里我使用了#,你可以使用?,@或任何其它字符满足上述条件.该:g命令的捕获是它最终需要一个命令,所以如果你在最后一个字符后面没有尾随空格,它就不会像你期望的那样执行搜索.而且,即使你正在使用\V,你仍然必须逃避反斜杠.

如果仍然没有为你削减它,这个Nabble帖子有一个建议,采用嵌入反斜杠和其他特殊Vim字符的文字字符串,并声称搜索它没有问题; 但它需要创建一个Vim功能,在您的环境中可能会或可能不会.


DrA*_*rAl 21

看看你的具体例子,可能最简单的方法(因为\ V在这里没有帮助)是使用?而不是/:那么你将不必逃避/s:

?((N/N)/(N/N))/N
Run Code Online (Sandbox Code Playgroud)

这将向后搜索而不是向前搜索,但是您可以在第一次搜索后始终使用"N"而不是"n"进行搜索.或者您可以按/向上光标键,以自动转义正斜杠.

但是,对于转义反斜杠,没有什么可以轻易做到的.我想你可以这样做:

:let @/ = escape(pattern, '\')
Run Code Online (Sandbox Code Playgroud)

然后n用来搜索,但它可能并不容易.我能想到的最好的是:

:command! -nargs=1 S let @/ = escape('<args>', '\')
Run Code Online (Sandbox Code Playgroud)

然后做:

:S (N)/(N+1)\(N)
n
Run Code Online (Sandbox Code Playgroud)


Bri*_*per 5

也许是这样的:

nmap <Leader>s :execute '/\V' . escape(input('/'), '\\/')<CR>
Run Code Online (Sandbox Code Playgroud)

它会给你一个/提示和行为,就像内置的搜索一样,但它不会像你一样搜索或其他类似的东西.