【问题标题】:How to remove multiple, repeating & unnecessary punctuation from string in C#?如何从 C# 中的字符串中删除多个、重复和不必要的标点符号?
【发布时间】:2017-10-29 12:46:28
【问题描述】:

考虑这样的字符串:

"This is a string....!"
"This is another...!!"
"What is this..!?!?"
...
// There are LOTS of examples of weird/angry sentence-endings like the ones above.

我想把末尾不必要的标点符号替换成这样:

"This is a string!"
"This is another!"
"What is this?"

我基本上做的是: - 按空间分割 - 检查字符串中的最后一个字符是否包含标点符号 - 开始用下面的模式替换

我尝试了一个非常大的“.Replace(string, string)”函数,但它不起作用 - 我猜必须有一个更简单的正则表达式。

文档:

返回一个新字符串,其中当前实例中出现的所有指定字符串都替换为另一个指定字符串。

还有:

由于此方法返回修改后的字符串,您可以将连续调用 Replace 方法链接在一起,以对原始字符串执行多次替换。

这里有什么问题。

编辑:所有建议的解决方案都可以正常工作!非常感谢你! 这是最适合我的项目的解决方案:

Regex re = new Regex("[.?!]*(?=[.?!]$)");
string output = re.Replace(input, "");

【问题讨论】:

  • 为此使用正则表达式。

标签: c# regex string


【解决方案1】:

您的解决方案几乎可以正常工作 (demo),唯一的问题是同一序列可以从不同位置开始匹配。例如,最后一行中的 ..!?!? 不是替换列表的一部分,因此 ..!?!? 被两个单独的匹配项替换,在输出中生成 ??

看起来您的策略非常简单:在多个标点字符链中,最后一个字符获胜。您可以使用正则表达式进行替换:

[!?.]*([!?.])

并将其替换为$1,即具有最后一个字符的捕获组:

string s;
while ((s = Console.ReadLine()) != null) {
    s = Regex.Replace(s, "[!?.]*([!?.])", "$1");
    Console.WriteLine(s);
}

Demo

【讨论】:

  • 谢谢!这很有道理,我会在我的例子中尝试一下!
【解决方案2】:

简单

[.?!]*(?=[.?!]$)

应该为你做。喜欢

Regex re = new Regex("[.?!]*(?=[.?!]$)");
Console.WriteLine(re.Replace("This is a string....!", ""));

这将替换所有标点符号,但最后一个什么都没有。

[.?!]* 匹配任意数量的连续标点字符,(?=[.?!]$) 是正向前瞻,确保它在字符串末尾留下一个。

See it here at ideone.

【讨论】:

    【解决方案3】:

    或者你可以不使用正则表达式:

        string TrimPuncMarks(string str)
        {
            HashSet<char> punctMarks = new HashSet<char>() {'.', '!', '?'};
    
            int i = str.Length - 1;
            for (; i >= 0; i--)
            {
                if (!punctMarks.Contains(str[i]))
                    break;
            }
    
            // the very last punct mark or null if there were no any punct marks in the end
            char? suffix = i < str.Length - 1 ? str[str.Length - 1] : (char?)null;
    
            return str.Substring(0, i+1) + suffix;
        }
    
        Debug.Assert("What is this?" == TrimPuncMarks("What is this..!?!?"));
        Debug.Assert("What is this" == TrimPuncMarks("What is this"));
        Debug.Assert("What is this." == TrimPuncMarks("What is this."));
    

    【讨论】:

    • suffix??"" 是什么意思?您的代码有效,但在这种情况下,如果 suffixnull,但如果 str.Substring(0, i + 1) + suffixnull,则合并运算符不会返回空字符串。
    • @NotADeveloper 是的,??"" 是多余的。谢谢。
    猜你喜欢
    • 2020-09-27
    • 1970-01-01
    • 2013-10-08
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多