54

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?

Hendrik
  • 4,849
  • 7
  • 46
  • 51

1 Answers1

74

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$
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Kent
  • 189,393
  • 32
  • 233
  • 301
  • Thanks. Why Do I have to surround the text before \@= with () ? – Hendrik Aug 22 '13 at 22:40
  • 1
    @Hendrik without the `()` how can the regex engine know, which part is the Zero-width matching part? – Kent Aug 22 '13 at 22:47
  • 2
    @Hendrik 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$` – FDinoff Aug 23 '13 at 01:23
  • 1
    where is the documentation for `\zs` and `\ze` ? I don't see anything at http://vimregex.com/#substitute – Maslow May 11 '16 at 14:35
  • 2
    @Maslow you are looking for it in wrong place... just open your vim, and `:h \zs` – Kent May 11 '16 at 14:47
  • 4
    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 – Llopeth Nov 21 '18 at 13:22
  • @Kent in my humble opinion very magic is even worse!! because you have to remember which escapings can or cannot be avoided. Its a complete mess – Llopeth Nov 21 '18 at 16:06
  • 1
    @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. – Kent Nov 21 '18 at 20:39