Barış Velioğlu
Barış Velioğlu

Reputation: 5827

A Regex replace case in .NET

I am trying to replace all numbers in a <number></number> element as xxx if the number length is 15 or 16.

for example <number>1234567812345678</number> -> <number>xxx</number>

I did something like below but it replace the numbers even if their' length is bigger than 16. How to prevent this case ?

string test = "<number>1234567812345678</number><number>12345671234567</number><number>1234567123456712345678</number>";

test = Regex.Replace(test, @"([\d]{15,16})", "xxx"); 

Unwanted output

<number>xxx</number><number>12345671234567</number><number>xxx345678</number>

Wanted output

 <number>xxx</number><number>12345671234567</number><number>1234567123456712345678</number>

Upvotes: 2

Views: 190

Answers (3)

Meta-Knight
Meta-Knight

Reputation: 17875

You didn't specify that the numbers should be preceded by <number> and followed by </number>. You can do it like this:

test = Regex.Replace(test, @"(?<=<number>)([\d]{15,16})(?=</number>)", "xxx"); 

Upvotes: 2

Brian Geihsler
Brian Geihsler

Reputation: 2087

Regex by default will replace substrings unless you tell it how the string is supposed to end. You need to surround your [\d]{15,16} with matchers against the tag like this:

Regex.Replace(test, @"<number>[\d]{15,16}</number>", @"<number>xxx</number>");

Upvotes: 1

Kendall Frey
Kendall Frey

Reputation: 44374

string test = "<number>1234567812345678</number><number>12345671234567</number><number>1234567123456712345678</number>";

test = Regex.Replace(test, @"(?<=>)\d{15,16}(?=<)", "xxx");

This makes sure that the number is preceded by a > and followed by a <, using lookaround.

Upvotes: 5

Related Questions