Powerslave
Powerslave

Reputation: 467

How to replace only a part of a Regex matched string in .NET?

Given the string: "+49 ( 0 ) 162 12345 0162"

And the regex: ^(+\s*4\s*9\s*(\s*0\s*)|+\s*4\s*9|0\s*0\s*4\s*9|0|(\s*0\s*))\s*(15|16|17)

It matches: "+49 ( 0 ) 16"

Now I want to replace everything before 16, so that results in "162 12345 0162".

I have so far:

        Regex regex = new Regex( @"^(\+\s*4\s*9\s*\(\s*0\s*\)|\+\s*4\s*9|0\s*0\s*4\s*9|0|\(\s*0\s*\))\s*(15|16|17)");
        string result = regex.Replace( "+49 ( 0 ) 162 12345 0162", "" );

But that returns "2 12345 0162".

Thank you!

Upvotes: 1

Views: 208

Answers (2)

Sangbok  Lee
Sangbok Lee

Reputation: 2228

Is (15|16|17) at the end really necessary? Removing it will give you desired result.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

(15|16|17) part of your pattern - the second capturing group - matches and captures 16. Thus, you need to replace with $2 backreference.

string result = regex.Replace( "+49 ( 0 ) 162 12345 0162", "$2" );

See the regex demo

enter image description here

Upvotes: 1

Related Questions