Vim regex capture groups

I have a list of words:

bau ceu diu fou gau 

I want to turn this list into:

 byau cyeu dyiu fyou gyau 

I tried the command:

 :%s/(\w)(\w\w)/\1y\2/g 

What do I need to change to get capture groups to work in Vim?

+72
vim regex regex-group capturing-group
Nov 11 '13 at 8:43
source share
4 answers

One way to fix this is to ensure that the pattern is enclosed in brackets:

 :%s/\(\w\)\(\w\w\)/\1y\2/g 

It’s slightly shorter (and even better) to use \v , which means that in the pattern after it all ASCII characters except '0'-'9' , 'a'-'z' , 'a'-'z' and '_' have special meaning:

 :%s/\v(\w)(\w\w)/\1y\2/g 

Cm:

+122
Nov 11 '13 at 8:46
source share

If you don't want to hide capture groups with backslashes (this is what you missed), add \v to turn the Vim regex engine into very magical mode:

 :%s/\v(\w)(\w\w)/\1y\2/g 
+31
Nov 11 '13 at 8:47
source share

You can also use this template, which is shorter:

 :%s/^./&y 
  • %s applies the template to the entire file.
  • ^. matches the first character of the string.
  • &y adds y after the pattern.
+20
May 28 '15 at 15:38
source share

You also need to avoid grouping grouping:

 :%s/\(\w\)\(\w\w\)/\1y\2/g 

This is a trick.

+8
Nov 11 '13 at 8:46
source share



All Articles