C# 删除连续数字之间的空白
我有一个字符串,我想从中删除数字之间的空白: 预期/预期结果将是:C# 删除连续数字之间的空白,c#,regex,C#,Regex,我有一个字符串,我想从中删除数字之间的空白: 预期/预期结果将是: "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: "te
"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"
您的正则表达式使用右边的数字
(\d)\s(\d)
匹配并捕获中的1
一些单词1 2 3 4
,然后匹配1个空格,然后匹配并使用(即添加到匹配值并推进正则表达式索引)2
。然后,正则表达式引擎尝试从当前索引中找到另一个匹配项,该索引已经在12
之后。因此,正则表达式不匹配23
,而是查找34
下面是一个图表,显示:
此外,请参见此处的匹配过程:
改为使用非消耗性的lookarounds:
见:
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"
您可以使用以下方法来避免:
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"
...
(哇,那些视觉表现很好-你是怎么得到的?我没有在屏幕上看到它们,还是我忽略了什么?我找到了调试器,但不是“工作流”调试器)(很抱歉,我没有看到它。这里有一个。澄清一下,我正在寻找。)@WiktorStribiżew和哪个工具可以查看进程中的正则表达式匹配?@EhsanSajjad我使用了调试器。@WiktorStribiżew感谢您通知我,我从来没有意识到,有一个。或者,您可以运行原始正则表达式两次。尽管积极的前瞻可能永远是最好的选择。为了好玩,这是一个不需要正则表达式的解决方案。我认为正则表达式是更好的解决方案。
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
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"
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"
...