What is the \& pattern in Vim's Regex

后端 未结 2 705
一个人的身影
一个人的身影 2020-12-30 05:19

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         


        
相关标签:
2条回答
  • 2020-12-30 06:07

    \& can be used to match a line containing two (or more) words in any order. For example,

    /.*one\&.*two\&.*three

    will find lines containing one, two and three in any order. The .* is necessary because each branch must start matching in the same place.

    Note, the last branch is the one that participates in any substitution. For example, applying the following substitution:

    s/.*one\&.*two\&.*three/<&>/

    on the line

    The numbers three, two, and one

    results in

    <The numbers three>, two, and one

    0 讨论(0)
  • 2020-12-30 06:15

    Explanation:

    \& is to \|, what the and operator is to the or operator. Thus, both concats have to match, but only the last will be highlighted.

    Example 1:

    (The following tests assume :setlocal hlsearch.)

    Imagine this string:

    foo foobar
    

    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.

    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.

    Example 2:

    /\c\v([^aeiou]&\a){4}.

    \c - ignore case

    \v - "very magic" (-> you don't have to escape the & in this case)

    (){4} - repeat the same pattern 4 times

    [^aeiou] - exclude these characters

    \a - alphabetic character

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

    0 讨论(0)
提交回复
热议问题