删除连续数字之间的空格

nnt*_*nty 32 c# regex

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

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

预期/期望的结果将是:

"Some Words 1234"
Run Code Online (Sandbox Code Playgroud)

但我检索以下内容:

"Some Words 12 34"
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

更多例子:

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"
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 44

你的正则表达式会消耗右边的数字.(\d)\s(\d)比赛和捕获1Some Words 1 2 3 4成组1,则匹配1个空白,然后匹配和消耗(即增加了匹配值和前进正则表达式指数)2.然后,正则表达式引擎尝试从当前索引中找到另一个匹配,即之后的匹配1 2.所以,正则表达式不匹配2 3,但发现3 4.

这是你的正则表达式演示和一个图表显示:

在此输入图像描述

另外,请在此处查看匹配过程:

在此输入图像描述

使用非消费的外观:

(?<=\d)\s+(?=\d)
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

在此输入图像描述

细节

  • (?<=\d) - 一个正面的lookbehind,匹配紧跟在数字前面的字符串中的位置
  • \s+ - 1+个空格
  • (?=\d) - 与字符串中的位置匹配的正向前瞻,后跟数字.

C#demo:

string test = "Some Words 1 2 3 4";
string result = Regex.Replace(test, @"(?<=\d)\s+(?=\d)", "");
Run Code Online (Sandbox Code Playgroud)

查看在线演示:

var strs = new List<string> {"Some Words 1 2 3 4", "Some Words That Should not be replaced 12 9 123 4 12", "test 9 8", "t e s t 9 8", "Another 12 000" };
foreach (var test in strs) 
{
    Console.WriteLine(Regex.Replace(test, @"(?<=\d)\s+(?=\d)", ""));
}
Run Code Online (Sandbox Code Playgroud)

输出:

Some Words 1234
Some Words That Should not be replaced 129123412
test 98
t e s t 98
Another 12000
Run Code Online (Sandbox Code Playgroud)

  • @BruceWayne请参阅https://jex.im/regulex - 但我必须手动编辑图像. (6认同)
  • (哇,这些可视化表示很整洁-您如何获得它们?我在https://regex101.com上看不到它们,还是我忽略了某些东西?我找到了调试器,但找不到“工作流”一个) (2认同)

Hei*_*nzi 44

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"
Run Code Online (Sandbox Code Playgroud)

您可以使用零宽度正向前瞻断言来避免这种情况:

string result = Regex.Replace(test, @"(\d)\s(?=\d)", @"$1");
Run Code Online (Sandbox Code Playgroud)

现在最后的数字不是比赛的一部分:

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"

...
Run Code Online (Sandbox Code Playgroud)