Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Regex Replace

Tags:

I think this is a pretty simple solution but I have been trying to find an answer for about an hour and can't seem to figure it out.

I'm trying to do a find/replace in Vim that would replace a series of numbers that begin with 103 and are followed by four digits to 123 followed by the same four digits, as such:

1033303 -> 1233303
1033213 -> 1233213

The closest I have come is this:

%s/103\d\{4}/123\0/g 

However this results in the entire number being matched by the \0, as such:

1033303 -> 1231033303

Thank you very much for any help

like image 556
80vs90 Avatar asked Aug 07 '12 16:08

80vs90


2 Answers

You're very close

%s/103\(\d\{4}\)/123\1/g 

The pattern between \( and \) is a sub-match that can be accessed by \1, \2 etc in the order of appearance. See :help \( for more information.

like image 130
Conner Avatar answered Sep 22 '22 23:09

Conner


Now w/o the capture group!

:%s/103\ze\d\{4}/123/g 

\ze will set the end of the match there. This allows for you match the whole pattern but only do the substitution on a portion of it.

:h /\ze :h /\zs 
like image 25
Peter Rincker Avatar answered Sep 25 '22 23:09

Peter Rincker