Removing whitespace between consecutive numbers

  • A+
Category:Languages

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" 

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: