【问题标题】:Removing whitespace between consecutive numbers删除连续数字之间的空格
【发布时间】:2019-02-26 10:17:59
【问题描述】:

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

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"

【问题讨论】:

  • 为了好玩,here 是一个无正则表达式的解决方案。我认为正则表达式是更好的解决方案。

标签: c# regex


【解决方案1】:

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"

...

【讨论】:

  • 或者,您可以运行原始正则表达式两次。尽管积极的前瞻可能总是最好的选择。
【解决方案2】:

您的正则表达式使用右边的数字。 (\d)\s(\d) 匹配并捕获 Some Words 1 2 3 4 中的 1 到组 1,然后匹配 1 个空格,然后匹配并使用(即添加到匹配值并推进正则表达式索引)2。然后,正则表达式引擎尝试从当前索引中找到另一个匹配项,即已经在1 2 之后。所以,正则表达式不匹配2 3,但找到3 4

这是your regex demo 和一个图表显示:

另外,匹配过程见这里:

使用非消耗性的环视代替

(?<=\d)\s+(?=\d)

regex demo

详情

  • (?&lt;=\d) - 与字符串中紧接在数字前面的位置相匹配的正向回溯
  • \s+ - 1+ 个空格
  • (?=\d) - 与字符串中的位置匹配的正向前瞻,紧跟数字。

C# 演示:

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

online demo

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

输出:

Some Words 1234
Some Words That Should not be replaced 129123412
test 98
t e s t 98
Another 12000

【讨论】:

  • (哇,这些视觉表示很简洁——你是怎么得到这些的?我在regex101.com 上没有看到它们,还是我忽略了什么?我找到了调试器,但不是“工作流程”一)
  • (抱歉出轨 - 我没看到。这是screenshot。澄清一下,我正在寻找this thingy。)
  • @WiktorStribiżew 以及在进程中查看正则表达式匹配的工具是什么?
  • @EhsanSajjad 我使用了regex101 调试器。
  • @WiktorStribiżew 感谢告知,我从来不知道,有一个
猜你喜欢
  • 2019-09-12
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多