我有这个字符串:
Corso Vittorio Emanuele II 9 20122 Milano
这个字符串最初是这样的格式:
Corso Vittorio Emanuele II 9
20122
Milano
所以我使用 Regex 表达式删除了 NewLine
:
var stringWithoutNewLine = Regex.Replace(text, "\t|\n|\r", string.Empty).Trim();
现在我尝试以这种方式删除空格:
return Regex.Replace(stringWithoutNewLine, @"\s+", string.Empty);
但它没有按预期工作,因为我得到了这个结果:
CorsoVittorioEmanueleII920122Milano
什么时候应该:
Corso Vittorio Emanuele II 9 20122 Milano
最佳答案
将正则表达式从 @"\s+"
更改为 @"\s{2,}"
。它将删除从 2 到(某种)无限数量重复的空格。然后,正如 Juharr 指出的那样,用一个空格替换:
Regex.Replace(yourString, @"\s{2,}", " ");
关于c# - 仅当超过一定大小时才从字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39792756/