2

Does vim allow us to assign names to capture groups for search/replace that can be used in place of \1, \2 etc... for back-references and substitution?

Like in in Python:

>>> import re
>>> s="ABCD HELLO, WORLD! 1234"
>>> print(re.sub(r"^(?P<foo>\w+).*?(?P<bar>\d+)$", r"\n\g<foo> \g<bar>\n", s))

ABCD 1234


Or Perl:

dade_murphy@darkstar$ \
> printf "ABCD HELLO, WORLD! 1234" \
>   | perl -pe 's/^(?<foo>\w+).*?(?<bar>\d+)$/\n$+{foo} $+{bar}\n/'

ABCD 1234


ie. something like this:

:s/^\(?P<foo>\w\+\)\s*$/\g<foo>/


Neither syntax seems to work. I'm guessing this is not supported-- it doesn't strike me as a feature that would be particularly sought after in a text editor. But search / Google aren't confirming either way, so here I am.

  • 5
    Idk about named captures, but numbered, yes. See help \1 i believe. – D. Ben Knoble Sep 11 at 20:16
  • 4
    Note possible. It has been requested years ago but was never implemented. – Christian Brabandt Sep 11 at 20:24
  • 2
    Capture groups are possible. Why would you want a named capture groups? – jdhao Sep 12 at 1:40
  • 1
    one potential advantage to named groups is the ability to have more than 9 (if implemented that way) – Mass Sep 12 at 3:28
  • 3
    @Mass one of the first patches I made for Vim were to move the limit from 9 capture groups to 99 groups. That was almost 10 years ago. It has never been merged (but rather we got a new second regexp engine :(). Back then I was working with CSV files quite often and that patch would have been very helpful, but oh well... – Christian Brabandt Sep 12 at 6:03
2

No, named capture groups are not available.

In fact, some design decisions in Vim actually expose the limit of 9 (numbered) capture groups, such as the matchlist() function, which returns a list of 10 strings for each of \0 through \9. (That doesn't mean named groups would be impossible, it's just exposing some internals showing this is quite an ingrained design decision.)

You can also go through the whole :help pattern-searches and you'll see no reference to named capture groups.

Vim also has some regexp features (namely \zs and \ze to mark the start and end of the match) that can replace the use of capture groups and are often more convenient to use in case you're only using capture groups to repeat them as part of the replacement.

So, in short, no, named capture groups are not available as of Vim 8.1.

  • 1
    Darn it! Oh well, kind of what I was expecting, but it's good to have it confirmed. Good answer, and thanks for the extra insights! – Z4-tier Sep 12 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.