如何从字符串中删除标点符号?

Tom*_*ter 64 c# string

对于这个问题的30秒内希望得到答案,我特意寻找C#

但在一般情况下,删除任何语言标点符号的最佳方法是什么?

我应补充一点:理想情况下,解决方案不需要您枚举所有可能的标点符号.

相关:Python中的条带标点符号

GWL*_*osa 103

new string(myCharCollection.Where(c => !char.IsPunctuation(c)).ToArray());
Run Code Online (Sandbox Code Playgroud)

  • LinQ永远不会让我感到惊讶. (5认同)
  • 对于$或^你可以使用`!char.IsSymbol(c)`验证.只是为了记录 (2认同)

Had*_*s32 18

为什么不简单:

string s = "sxrdct?fvzguh,bij.";
var sb = new StringBuilder();

foreach (char c in s)
{
   if (!char.IsPunctuation(c))
      sb.Append(c);
}

s = sb.ToString();

RegEx的使用通常比简单的char操作慢.那些LINQ操作看起来对我来说太过分了.你不能在.NET 2.0中使用这样的代码......


Joa*_*uer 13

假设"最好"意味着"最简单",我建议使用这样的东西:

String stripped = input.replaceAll("\\p{Punct}+", "");
Run Code Online (Sandbox Code Playgroud)

这个例子适用于Java,但所有足够现代的Regex引擎都应该支持这个(或类似的东西).

编辑:Unicode-Aware版本是这样的:

String stripped = input.replaceAll("\\p{P}+", "");
Run Code Online (Sandbox Code Playgroud)

第一个版本只查看ASCII中包含的标点字符.


Bri*_*Low 11

描述意图,最容易阅读(恕我直言)和最佳表现:

 s = s.StripPunctuation();
Run Code Online (Sandbox Code Playgroud)

实施:

public static class StringExtension
{
    public static string StripPunctuation(this string s)
    {
        var sb = new StringBuilder();
        foreach (char c in s)
        {
            if (!char.IsPunctuation(c))
                sb.Append(c);
        }
        return sb.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是使用Hades32的算法,这是发布的最佳表现.


Ant*_*ton 8

您可以使用regex.replace方法:

 replace(YourString, RegularExpressionWithPunctuationMarks, Empty String)
Run Code Online (Sandbox Code Playgroud)

由于这会返回一个字符串,因此您的方法将如下所示:

 string s = Regex.Replace("Hello!?!?!?!", "[?!]", "");
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你可以用"s?siticitated"替换"[?!]":

(\p{P})
Run Code Online (Sandbox Code Playgroud)

这应该找到任何标点符号.


Nic*_*aro 6

这个帖子太旧了,但我不能发布更优雅的(IMO)解决方案.

string inputSansPunc = input.Where(c => !char.IsPunctuation(c)).Aggregate("", (current, c) => current + c);
Run Code Online (Sandbox Code Playgroud)

这是LINQ没有WTF.


The*_*TXI 2

最脑残的简单方法是使用 string.replace

我想象的另一种方式是 regex.replace 并让正则表达式中包含所有适当的标点符号。