[英]A regex pattern '{.*}' does not work in Vim as (I) expected
I have a one-line text file opened in Vim: 我在Vim中打开了一个单行文本文件:
a{b} {c}
I want to match strings enclosed by curly braces. 我想匹配用大括号括起来的字符串。 If my cursor is at line 1 col 1 of the file and I do 如果我的光标位于文件的第1行,我会
:call search('{.*}', 'W')
The cursor will go to the first '{' after the character 'a'. 光标将移到字符“ a”之后的第一个“ {”。
But if I repeat the search, the cursor does not go to the second '{' which is between 'b' and 'c', and echo search('{.*}', 'W')
returns 0. 但是,如果我重复搜索,则光标不会移至位于“ b”和“ c”之间的第二个“ {”,并且echo search('{.*}', 'W')
返回0。
Why? 为什么?
EDIT: Let me address the answer by @romainl 编辑:让我解决@romainl的答案
I understand that *
is greedy, and I am OK matching {b} {c}
first. 我知道*
是贪婪的,我可以先匹配{b} {c}
。
However, when the cursor is under the first {
, the pattern should still be able to match {c}
because {c}
is after the cursor and agrees with the pattern. 但是,当光标在第一个{
下方时,该模式仍应能够与{c}
匹配,因为{c}
在光标之后并且与该模式一致。
romainl is right, vim apparently doesn't ignore the characters before the cursor when using search(). romainl是正确的,在使用search()时,vim显然不会忽略光标之前的字符。
If you still wanna use a greedy operator inside the braces you can do this 如果您仍想在括号内使用贪婪的运算符,则可以执行此操作
echo search('\m\%#.\{-1,}\zs{.*}', 'W')
\\%#
matches only after the cursor position, .\\{-1,}
makes sure we match anything AFTER the first { if we're on it, \\zs
excludes these from the actual match \\%#
仅在光标位置.\\{-1,}
之后匹配.\\{-1,}
确保我们在第一个{之后(如果在上面)匹配任何内容, \\zs
从实际匹配中排除这些内容
*
is greedy, it will match as many instances of the previous pattern as possible. *
是贪婪的,它将与先前模式的尽可能多的实例匹配。 This means that {.*}
will match this: 这意味着{.*}
将与此匹配:
a{b} {c}
^^^^^^^
instead of the desired: 而不是所需的:
a{b} {c}
^^^
You should use a non-greedy pattern like \\{-}
: 您应该使用\\{-}
这样的非贪婪模式:
{.\{-}}
which will match: 将会匹配:
a{b} {c}
^^^
and: 和:
a{b} {c}
^^^
on next call. 在下一个电话。
When trying to find the right search pattern, it is generally useful to do so on the command-line with 'incsearch'
on. 当试图找到正确的搜索模式时,通常在命令行上启用'incsearch'
。 Try it with your original pattern and you will immediately see what is wrong. 用您的原始模式尝试一下,您将立即发现问题所在。
See :help pattern-multi-items
and :help \\{
. 参见:help pattern-multi-items
和:help \\{
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.