2

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>
1
  • 1
    You want to specify that it is preceded by something that is not a digit and followed by something that is not a digit. Commented May 16, 2012 at 14:27

3 Answers 3

5
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.

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

1 Comment

This is more exactly what I wanted. Thank you very much. I will mark it when I can.
2

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"); 

Comments

1

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>");

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.