我有一个字符串,我想从中删除数字之间的空格:
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/