2

我每天都在使用 vim 来处理文本和编写代码。但是,每次我必须执行任何替换或任何类型的正则表达式工作时,它都会让我发疯,我必须切换到 sublime。我想知道,转动这个的正确方法是什么:

<img src="whatever.png"/>
<img src="x.png"/>

进入

<img src="<%= image_path("whatever.png") %>"/>
<img src="<%= image_path("x.png") %>"/>

在崇高的情况下,我可以将其用作搜索的正则表达式:src="(.*?.png)"并将其用作替换的正则表达式:src="<%= asset_path("\1") %>"。在 vim 中,如果我这样做::%s/\vsrc="(.*?.png)/src="<%= asset_path("\1") %>"/g我得到:

E62: Nested ?
E476: Invalid command

我做错了什么?

4

3 回答 3

5

正如@nhahtdh 所说,Vim 的正则表达式方言\{-}用作非贪婪量词。如果您使用非常神奇的标志,那就是{-}. 所以你的命令变成:

:%s/\vsrc="(.{-}.png)/src="<%= asset_path("\1") %>"/g

.但是,您并没有.png因此逃脱:

:%s/\vsrc="(.{-}\.png)/src="<%= asset_path("\1") %>"/g

但我们仍然可以做得更好!通过使用\zsand\ze我们可以避免重新输入src="位。\zs\ze标记将发生替换的比赛的开始和结束。

:%s/\vsrc="\zs(.\{-}\.png)"/<%= image_path("\1") %>"/g

However we still are not done because we can take it one step further if we carefully choose where we put \zs and \ze then we can use vim's & in the substitution. It is like \0 in Perl's regex syntax. Now we don't need any capture groups which nullifies the need for the very magic flag.

:%s/src="\zs.\{-}\.png\ze"/<%= image_path("&") %>/g

For more help see the following documentation:

:h /\zs
:h /\{-
:h s/\&
于 2013-09-13T14:28:25.707 回答
3

根据这个网站,vim 中惰性量词的语法与类似 Perl 的正则表达式中使用的语法不同。

让我引用网站:

                                                          */\{-*
\{-n,m}   matches n to m of the preceding atom, as few as possible
\{-n}     matches n of the preceding atom
\{-n,}    matches at least n of the preceding atom, as few as possible
\{-,m}    matches 0 to m of the preceding atom, as few as possible
\{-}      matches 0 or more of the preceding atom, as few as possible
          {Vi does not have any of these}

          n and m are positive decimal numbers or zero

                                                        *non-greedy*
If a "-" appears immediately after the "{", then a shortest match
first algorithm is used (see example below).  In particular, "\{-}" is
the same as "*" but uses the shortest match first algorithm.
于 2013-09-13T12:32:20.660 回答
2

:%s/"\(.*\)"/"<%= image_path("\1") %>"/g

双引号是主要模式。我们想要捕获的所有内容都会被放入一个组\( \)中,以便我们以后可以通过\1.


如果你用得很魔法,你就得逃之夭夭了=,于是\vsrc\=(.*).png"。所以用你的方式答案是:

:%s/\vsrc\="(.*\.png)"/src="<%= image_path("\1") %>"/g

很容易看到你:set hlsearch,然后玩弄/. :)

于 2013-09-13T12:31:38.090 回答