Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy regular expression (regex) match in vim

Tags:

regex

vim

In vim, using regular expressions or patterns, how can a match be copied so that the match is put directly after itself, without replacing the match?

For example, I'd like to copy everything before a comma on a line, to after the comma:

one,
two,
three,
four,

... would then become:

one,one
two,two
three,three
four,four

I can match with .*,, or globally with %s/.*,. I can even do a zero-width match with .*,\@<= or even .*,\zs. But I can't figure out where to go from here.

like image 876
Aaron Thomas Avatar asked Apr 15 '26 12:04

Aaron Thomas


1 Answers

Use group capturing. To use group capturing, put part of your regex between parenthesis (they need to be escaped), then that will be placed in subgroup one. Everything in the next pair of parenthesis will be placed in subgroup two, etc. for up to 9 groups. You can then reference this group in the replace part of your substitution. For example:

:%s/\(.*\),/\1,\1

This means capture anything up to a comma, and call it group \1. Then, replace this text with (group1),(group1). You could also do

:%s/\(.*\),/&\1

since & means "The entire matched text" (same as \0).

You could also use very magic e.g. \v to make this more readable. For example:

:%s/\v(.*),/&\1

As a side note, the simpler way to achieve the same affect would be to use :%norm, which applies a set of keystrokes to every line. For example, you could do

:%norm yt,f,p

Recommended reading: http://vimregex.com/

like image 64
DJMcMayhem Avatar answered Apr 18 '26 02:04

DJMcMayhem