Vim positive lookahead regex
Asked Answered
F

1

55

I am still not so used to the vim regex syntax. I have this code:

rename_column :keywords, :textline_two_id_4, :textline_two_id_4

I would like to match the last id with a positive lookahead in VIMs regex syntax.

How would you do this?

\id@=_\d$

This does not work.

This perl syntax works:

id(?=_\d$)

Edit - the answer:

/id\(_\d$\)\@=

Can someone explain the syntax?

Footprint answered 22/8, 2013 at 22:14 Comment(0)
R
75

If you check the vim help, there is not much to explain: (:h \@=)

\@=     Matches the preceding atom with zero width. {not in Vi}
        Like "(?=pattern)" in Perl.
        Example             matches
        foo\(bar\)\@=       "foo" in "foobar"
        foo\(bar\)\@=foo    nothing

This should match the last id:

/id\(_\d$\)\@=

save some back slashes with "very magic":

/\vid(_\d$)@=

actually, it looks more straightforward to use vim's \zs \ze:

id\ze_\d$
Reception answered 22/8, 2013 at 22:34 Comment(8)
Thanks. Why Do I have to surround the text before \@= with () ?Footprint
@Footprint without the () how can the regex engine know, which part is the Zero-width matching part?Reception
@Footprint the parentheses are necessary if the things before the lookahead are a group of atoms. In your case you have three atoms _,\d,and $. So without out the parentheses the lookahead only looks for a $ which isn't very useful. The parentheses are treated as one atom so you can lookahead for _\d$Fizzy
where is the documentation for \zs and \ze ? I don't see anything at vimregex.com/#substituteBlub
@Blub you are looking for it in wrong place... just open your vim, and :h \zsReception
<rant> Regex syntax is already awful but vim regex syntax with all the necessary escaping and obscure non standard constructs manages to make things 10 times worse </rant>Ambulator
@Reception in my humble opinion very magic is even worse!! because you have to remember which escapings can or cannot be avoided. Its a complete messAmbulator
@AKludges if you cannot say the difference between BRE ERE PCRE, yes, escaping in regex is confusing. If you have to work with regex often, I suggest learning it. otherwise, ask Q here or google, you can solve your problem too. good luck.Reception

© 2022 - 2024 — McMap. All rights reserved.