Is there a way to do negative lookahead in vim regex?

后端 未结 5 1723
一生所求
一生所求 2021-01-31 15:40

In Vim, is there a way to search for lines that match say abc but do not also contain xyz later on the line? So the following lines would match:

<
相关标签:
5条回答
  • 2021-01-31 15:52

    Your attempt was pretty close; you need to pull the .* that allows an arbitrary distance between the match and the asserted later non-match into the negative look-ahead:

    /abc\(.*xyz\)\@!
    

    I guess this works because the non-match is attempted for all possible matches of .*, and only when all branches have been exhausted is the \@! declared as fulfilled.

    0 讨论(0)
  • 2021-01-31 15:54

    I think I'd write this as /abc\(\(xyz\)\@!.\)*$

    I'm not sure whether this is faster than other suggestions (I think it might be since it tests each position only once) but it makes conceptual sense as:

    "abc followed by anything which is not xyz, any number of times until end of line"

    I like that better than "abc followed by anything not followed by xyz" as in the other patterns mentioned.

    0 讨论(0)
  • 2021-01-31 15:58

    I always find it weird, that you need to escape brackets in vim, so I try to use the "very magic" mode most of the time, activated with \v:

    /\vabc(.*xyz)@!
    
    0 讨论(0)
  • 2021-01-31 16:09

    This works for me /abc\(.*xyz\)\@!

    0 讨论(0)
  • 2021-01-31 16:11

    Although your question is about lookahead, I found it while searching for lookbehind. Thus, I post the solution to lookbehind so that others may find it.

    If you search for pattern2 not preceded by pattern1, that is negative lookbehind, search for:

    \(pattern1\)\@<!pattern2
    
    0 讨论(0)
提交回复
热议问题