Mad Dog Tannen
Mad Dog Tannen

Reputation: 7244

RegEx to replace just part of the match

Ive had a look in some similar topics but wasnt able to located what im looking for so im asking a new question.

Is it possible to replace just a part of the string that matches the RegEx?

For instance

I want to replace 00NN to +NN . Just doing a simple replace on all 00 to + is not a option.

Below RegEx locates 2 zeros and 2 following numbers between 1-9.

Dim PhoneNumber AS String = Regex.Replace(IndexString, "([0][0][1-9]{2})", "+")

This replaces the entire 00NN to +, if is possible to have the replace keep the following NN so it replaces 00NN to +NN

Upvotes: 1

Views: 882

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

Yes, there are two ways to do this:

  1. Use a capturing group to store the part you want to keep:

    Dim PhoneNumber AS String = Regex.Replace(IndexString, "\b00([1-9]{2})", "+$1")

    Here, the parentheses capture the relevant part of the regex (they are numbered sequentially), and you can refer back to their contents in the replace string using $1 for the match of the first group, $2 for the second group etc. (and $0 for the entire match).

  2. Use a positive lookahead assertion:

    Dim PhoneNumber AS String = Regex.Replace(IndexString, "\b00(?=[1-9]{2})", "+")

    Here, (?=...) only asserts that it's possible to match ... at the current position without actually making it part of the match. This solution is probably faster than the first solution.

One more thing: You should use a word boundary anchor (\b) to make sure that you don't accidentally match 00 in the middle of a number - you probably don't want 00493010023456 to become +49301+23456, do you?

Upvotes: 5

Robin
Robin

Reputation: 9644

You can use lookaheads to match only what you want:

Regex.Replace(IndexString, "00(?=[1-9]{2}))", "+")

The (?=...) is a zero width assertion that matches only if what's inside matches, so it will perform the check you want without selecting the NN.

Upvotes: 2

Related Questions