c# - 删除连续数字之间的空格

标签 c# regex

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

string test = "Some Words 1 2 3 4";
string result = Regex.Replace(test, @"(\d)\s(\d)", @"$1$2");

预期/期望的结果将是:

"Some Words 1234"

但我检索到以下内容:

"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 继续搜索上一个匹配项之后:

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"

您可以使用 zero-width positive lookahead assertion为了避免这种情况:

string result = Regex.Replace(test, @"(\d)\s(?=\d)", @"$1");

现在最后一位数字不是匹配的一部分:

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"

...

关于c# - 删除连续数字之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54883163/

相关文章:

c# - MYSQL SQL语法错误c#

c# - 避免在 Type.GetType() 中给出命名空间名称

正则表达式查找由一两个单词分隔的 2 个单词

php - 正则表达式麻烦

正则表达式可在字符串中查找特殊字符,但有一些异常(exception)

regex - Apache mod_alias Redirect匹配除特定模式之外的所有内容

c# - 如何确定存储过程是否需要参数?

c# - 包装单个方法的方法

c# - 将图像管道传输到 FFmpeg 标准输入

c# - 使用正则表达式匹配 SQL 查询