26

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

1

4 Answers 4

37

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.

Sign up to request clarification or add additional context in comments.

Comments

10

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

3 Comments

Would .* after \ze do the trick once everuthing after it os ignored?
Yes, it would prevent more matches on the same line
This worked here: :%s,103\ze.*,123,g changing delimiter (fast to type) and matching all subsequent chars with .* which will be ignored on substitution.
4

Use a capturing group:

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

Comments

2

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.