I have a string, from which I want to remove the whitespaces between the numbers:
string test = "Some Words 1 2 3 4"; string result = Regex.Replace(test, @"(\d)\s(\d)", @"$1$2");
the expected/desired result would be:
"Some Words 1234"
but I retrieve the following:
"Some Words 12 34"
What am I doing wrong here?
Further examples:
Input: "Some Words That Should not be replaced 12 9 123 4 12" Output: "Some Words That Should not be replaced 129123412" Input: "test 9 8" Output: "test 98" Input: "t e s t 9 8" Output: "t e s t 98" Input: "Another 12 000" Output: "Another 12000"
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
Regex.Replace continues to search after the previous match:
Some Words 1 2 3 4 ^^^ first match, replace by "12" Some Words 12 3 4 ^ +-- continue searching here Some Words 12 3 4 ^^^ next match, replace by "34"
You can use a zero-width positive lookahead assertion to avoid that:
string result = Regex.Replace(test, @"(\d)\s(?=\d)", @"$1");
Now the final digit is not part of the match:
Some Words 1 2 3 4 ^^? first match, replace by "1" Some Words 12 3 4 ^ +-- continue searching here Some Words 12 3 4 ^^? next match, replace by "2" ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With