什么是\&Vim 正则表达式中的模式 [英] What is the \& pattern in Vim's Regex
问题描述
我最近在 Vim 正则表达式内置函数中遇到了分支说明符.\&
上的 Vim 帮助部分包含以下内容:
I recently came across the branch specifier in Vim regex builtins. Vim's help section on \&
contains this:
A branch is one or more concats, separated by "\&". It matches the last
concat, but only if all the preceding concats also match at the same
position. Examples:
"foobeep\&..." matches "foo" in "foobeep".
".*Peter\&.*Bob" matches in a line containing both "Peter" and "Bob"
目前尚不清楚它是如何使用的以及用于什么目的.很好地解释它的作用和使用方式会很棒.
It's not clear how it is used and what it is used for. A good explanation of what it does and how it is used would be great.
要清楚,这是不是在替换中使用的&
(替换为完整匹配),这是\&
在模式中使用.
To be clear this is not the &
(replace with whole match) used in a substitution, this is the \&
used in a pattern.
示例用法:
/\c\v([^aeiou]&\a){4}
用于搜索4个连续的辅音(取自vim提示).
Used to search for 4 consecutive consonants (Taken from vim tips).
推荐答案
说明:
\&
对应于 \|
,就像 and 运算符对应于 or 运算符.因此,两个 concat 必须匹配,但只有最后一个会突出显示.
\&
is to \|
, what the and operator is to the or operator. Thus, both concats have to match, but only the last will be highlighted.
示例 1:
(以下测试假设 :setlocal hlsearch
.)
想象一下这个字符串:
foo foobar
现在,/foo
将在两个单词中突出显示 foo
.但有时您只想匹配 foobar
中的 foo
.那么你必须使用 /foobar\&foo
.
Now, /foo
will highlight foo
in both words. But sometimes you just want to match the foo
in foobar
. Then you have to use /foobar\&foo
.
反正就是这样.经常使用吗?到目前为止,我还没有看到它超过几次.在这种简单的情况下,大多数人可能会使用零宽度原子.例如.可以通过 /foo\zebar
完成与本示例相同的操作.
That's how it works anyway. Is it often used? I haven't seen it more than a few times so far. Most people will probably use zero-width atoms in such simple cases. E.g. the same as in this example could be done via /foo\zebar
.
示例 2:
/\c\v([^aeiou]&\a){4}
.
\c
- 忽略大小写
\v
- 非常神奇"(-> 在这种情况下,您不必转义 &
)
\v
- "very magic" (-> you don't have to escape the &
in this case)
(){4}
- 重复相同的模式 4 次
(){4}
- repeat the same pattern 4 times
[^aeiou]
- 排除这些字符
\a
- 字母字符
因此,这个相当令人困惑的正则表达式将匹配 xxxx
、XXXX
、wXyZ
或 WxYz
但不匹配AAAA
或 xxx1
.简单来说:匹配任何不包含 'a'、'e'、'i'、'o' 或 'u' 的 4 个字母字符的字符串.
Thus, this, rather confusing, regexp would match xxxx
, XXXX
, wXyZ
or WxYz
but not AAAA
or xxx1
. Putting it in simple terms: Match any string of 4 alphabetic characters that doesn't contain either 'a', 'e', 'i', 'o' or 'u'.
这篇关于什么是\&Vim 正则表达式中的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!