Removing whitespace between consecutive numbers

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"

...

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)