1

I have a situation where commas are stripped when they shouldn't be, e.g.,

John 3:16,18,4:2 becomes John 3:16 18 4:2

I would like to put the commas back, and thought I could do it with

string strRegex = @"(\d+)\s+(\d+)";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"John 3:16 17 4:3";
string strReplace = @"$1,$2";

return myRegex.Replace(strTargetString, strReplace);

but this just gives me

John 3:16,18 4:2

What am I missing?

2 Answers 2

5

Use a lookbehind and lookahead so the digits are not a part of your match:

string strRegex = @"(?<=\d)\s+(?=\d)";
...
string strReplace = @",";
Sign up to request clarification or add additional context in comments.

Comments

1

You can try something with lookbehind:

@"(?<=\d)\s+(\d+)"

and replace with

,$1

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.