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

时间:2009-01-07 19:05:06

标签: c# string

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

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

我应该添加:理想情况下,解决方案不会要求您枚举所有可能的标点符号。

相关:Strip Punctuation in Python

15 个答案:

答案 0 :(得分:99)

new string(myCharCollection.Where(c => !char.IsPunctuation(c)).ToArray());

答案 1 :(得分: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中使用这样的代码......

答案 2 :(得分:13)

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

String stripped = input.replaceAll("\\p{Punct}+", "");

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

编辑:Unicode-Aware版本将是:

String stripped = input.replaceAll("\\p{P}+", "");

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

答案 3 :(得分:11)

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

 s = s.StripPunctuation();

实施:

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();
    }
}

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

答案 4 :(得分:8)

您可以使用regex.replace方法:

 replace(YourString, RegularExpressionWithPunctuationMarks, Empty String)

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

 string s = Regex.Replace("Hello!?!?!?!", "[?!]", "");

如果您愿意,可以将“[?!]”替换为更加干扰的内容:

(\p{P})

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

答案 5 :(得分:6)

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

string inputSansPunc = input.Where(c => !char.IsPunctuation(c)).Aggregate("", (current, c) => current + c);

这是LINQ没有WTF。

答案 6 :(得分:4)

根据GWLlosa的想法,我能够想出极其难看的但是工作:

string s = "cat!";
s = s.ToCharArray().ToList<char>()
      .Where<char>(x => !char.IsPunctuation(x))
      .Aggregate<char, string>(string.Empty, new Func<string, char, string>(
             delegate(string s, char c) { return s + c; }));

答案 7 :(得分:3)

最聪明的做法是使用string.replace

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

答案 8 :(得分:2)

如果您想使用它来标记文本,您可以使用:

new string(myText.Select(c => char.IsPunctuation(c) ? ' ' : c).ToArray())

答案 9 :(得分:2)

对于任何想通过RegEx这样做的人:

此代码显示了完整的RegEx替换过程,并提供了仅在字符串中保留字母,数字和空格的示例Regex-用空字符串替换所有其他字符:

//Regex to remove all non-alphanumeric characters
System.Text.RegularExpressions.Regex TitleRegex = new 
System.Text.RegularExpressions.Regex("[^a-z0-9 ]+", 
System.Text.RegularExpressions.RegexOptions.IgnoreCase);

string ParsedString = TitleRegex.Replace(stringToParse, String.Empty);

return ParsedString;

答案 10 :(得分:1)

这是使用linq稍微不同的方法。我喜欢AviewAnew,但这避免了聚合

        string myStr = "Hello there..';,]';';., Get rid of Punction";

        var s = from ch in myStr
                where !Char.IsPunctuation(ch)
                select ch;

        var bytes = UnicodeEncoding.ASCII.GetBytes(s.ToArray());
        var stringResult = UnicodeEncoding.ASCII.GetString(bytes);

答案 11 :(得分:1)

$newstr=ereg_replace("[[:punct:]]",'',$oldstr);

答案 12 :(得分:1)

我遇到了同样的问题,并担心每次检查都会调用IsPunctuation对性能产生影响。

我发现了这篇文章:http://www.dotnetperls.com/char-ispunctuation

各行:char.IsPunctuation还在ASCII之上处理Unicode。 该方法匹配包含控制字符的一堆字符。通过定义,这种方法既沉重又昂贵。

最重要的是,我最终没有采用它,因为它对我的ETL过程有性能影响。

我去了dotnetperls的自定义实现。

而且,请注意以下是从前面的答案中推导出的一些代码,以获取所有标点字符的列表(不包括对照字符):

var punctuationCharacters = new List<char>();

        for (int i = char.MinValue; i <= char.MaxValue; i++)
        {
            var character = Convert.ToChar(i);

            if (char.IsPunctuation(character) && !char.IsControl(character))
            {
                punctuationCharacters.Add(character);
            }
        }

        var commaSeparatedValueOfPunctuationCharacters = string.Join("", punctuationCharacters);

        Console.WriteLine(commaSeparatedValueOfPunctuationCharacters);

干杯, 安德鲁

答案 13 :(得分:0)

#include<string>
    #include<cctype>
    using namespace std;

    int main(int a, char* b[]){
    string strOne = "H,e.l/l!o W#o@r^l&d!!!";
    int punct_count = 0;

cout<<"before : "<<strOne<<endl;
for(string::size_type ix = 0 ;ix < strOne.size();++ix)   
{   
    if(ispunct(strOne[ix])) 
    {
            ++punct_count;  
            strOne.erase(ix,1); 
            ix--;
    }//if
}
    cout<<"after : "<<strOne<<endl;
                  return 0;
    }//main

答案 14 :(得分:0)

对于长字符串,我使用它:

var normalized = input
                .Where(c => !char.IsPunctuation(c))
                .Aggregate(new StringBuilder(),
                           (current, next) => current.Append(next), sb => sb.ToString());

比使用字符串连接要好得多(虽然我同意它不太直观)。

相关问题