2

I want to use the .NET Regex Replace method to separate numbers in a string.

String:"Delivery order #135670 is ready for pick up."

Replacement String:"Delivery order # 1 3 5 6 7 0 is ready for pick up."

This is as far as I've gotten.

Matching Pattern:((?<=\#)\d+)

I think this means: If a hash sign is the previous character, match one or more decimal digits. This pattern can be matched one time.

I have no idea how to do the replacement pattern.

If this seems to you like an odd thing to do, it's a way to get a speech synthesizer to speak "number one three five six seven zero" instead of "number one hundred thirty five thousand six hundred seventy".

4 Answers 4

1

We can use a MatchEvaluator (lambda) to add spaces:

string value = "Delivery order #135670 is ready for pick up.";
Regex r = new Regex(@"(#\d+)");
string result = r.Replace(value, m => string.Join(" ", 
                          m.Captures[0].Value.ToCharArray()));
//result = "Delivery order # 1 3 5 6 7 0 is ready for pick up.";

The regex (#\d+) does the following:

enter image description here

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

Comments

0

Use this pattern and in the replacement part, replace the matched ones with a space character.

(?<=\d|#)(?! )

DEMO

Comments

0

Here is the one-liner you're looking for:

String replaced = Regex.Replace(yourString, @"(?=\d)", " ");

In the regex demo, look at the substitutions pane at the bottom.

Explanation

  • The regex matches a position, not characters. This is called a zero-width match.
  • The lookahead (?=\d) asserts that what follows is a digit. If you want to be exact about it, you could use (?=\[0-9]) as .NET \d also matches Thai digits and so on, but that doesn't seem like a big risk here
  • We replace with a space.

Reference

Comments

0

Thanks to everyone for your help. After reading the advice of Bas, zx81 and Avinash I put together the following, which is being used successfully in the application.

Regex regex = new Regex(@"(?<=\d|#)");
message = regex.Replace(message, " ");

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.