首先,我允许字符串只有几个标点符号,例如只有点和逗号。这里没有显示,因为没有必要,只是为了知道。
所以如果我的字符串是:
string str = "hello,world,,,hello,, world... world ,,,, world ...";
然后我不允许一次重复这个标记:
string filtr1 = Regex.Replace(str, @"(\.|,){1,}", m => m.Value.First().ToString());
然后如果单词之间用标点符号合并,我用白色空格替换它并在其位置保留标记:
string filtr2 = Regex.Replace(filtr1, @"[\,\.]", (m) => m + " ");
并且在单词之间只允许一个空格:
string result = Regex.Replace(filtr2, @"\s+", " ");
所以现在我的结果看起来像这样:
hello, world, hello, world. world , world .
但我也需要这里,如果用户在标点符号前键入空格," hello,world" 如何在特定符号点和逗号之前不允许使用空格得到这个结果"你好,世界" 对于整个处理过的字符串结果应该是这样的:
hello, world, hello, world. world, world.
答案 0 :(得分:0)
如果你有一点创意Mickbt,你可以在一个表达式中完成这一切。
尝试搜索:
\s*(\.|,){1,}\s*
并替换为:\1
(注意\1
后面有空格)。 Example
在您的情况下,代码如下所示:
string result = Regex.Replace(str, @"\s*(\.|,){1,}\s*", "$1 ");
祝你好运!
答案 1 :(得分:0)
首先规范化白色空格,然后更容易编写标点符号模式:
string result = Regex.Replace(str, @"\s+", " ");
result = Regex.Replace(result, @" ?([.,]) ?(?:\1 ?)*", "$1 ");