删除连续数字之间的空格 [英] Removing whitespace between consecutive numbers

查看:64
本文介绍了删除连续数字之间的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想从中删除数字之间的空格 :

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");

预期/期望结果将是:

"Some Words 1234"

但是我检索到以下内容:

but I retrieve the following:

"Some Words 12 34"

我在做什么错了?

更多示例:

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继续在 之后的上一个匹配项中进行搜索:

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"

...

这篇关于删除连续数字之间的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆