Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing whitespace between consecutive numbers

Tags:

c#

regex

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" 
like image 206
aues Avatar asked Feb 26 '19 10:02

aues


People also ask

How do you remove spaces between numbers in Python?

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.

How do I remove spaces and numbers in a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.


1 Answers

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"  ... 
like image 92
Heinzi Avatar answered Oct 03 '22 23:10

Heinzi