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

对于这个问题中希望在30秒内得到答案的部分,我特别需要查找 C #

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

我应该补充一点: 理想情况下,解决方案不需要你列举所有可能的句读。

相关阅读: Python 中的条形标点符号

84525 次浏览

最简单的方法就是使用 string.place

另一种方法是使用 regex.place,并在正则表达式中包含所有适当的句读。

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

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

这个示例适用于 爪哇咖啡,,但是所有足够现代的 Regex 引擎都应该支持这个(或类似的东西)。

编辑: Unicode-Aware 版本如下:

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

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

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

可以使用 regex.place 方法:

 replace(YourString, RegularExpressionWithPunctuationMarks, Empty String)

因为它返回一个字符串,所以你的方法看起来像这样:

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

如果你愿意,你可以用一些更复杂的词来代替“[ ? ! ]”:

(\p{P})

应该能找到标点符号。

基于 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; }));

这里有一个使用 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);

为什么不简单地说:

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


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


s = sb.ToString();

正则表达式的使用通常比简单的字符操作慢。那些 LINQ 行动对我来说太过分了。这样的代码不能用在。NET 2.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

描述意图,易于阅读(IMHO)和最佳性能:

 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的算法,这是最好的性能的束张贴。

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

这个帖子太老了,但是如果我不发布一个更优雅的(IMO)解决方案,那就是我的失职。

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

这是没有卧槽的 LINQ。

对于长字符串,我使用:

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

比使用字符串串联要好得多(尽管我同意它不那么直观)。

我也面临同样的问题,并且担心对每个检查都调用 IsPuntuation 会对性能造成影响。

我发现了这个帖子: http://www.dotnetperls.com/char-ispunctuation

在 ASCII 之上,char.IsPunctuation 还处理 Unicode。 该方法匹配包括控制字符在内的一组字符。

底线是我最终没有采用它,因为它对我的 ETL 流程的性能有影响。

我选择了 dotnetperl 的自定义实现。

仅供参考,下面是从前面的答案中推导出的一些代码,可以得到所有标点符号的列表(不包括控制符号) :

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

干杯, 安德鲁

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

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

对于任何想通过正则快递做到这一点的人:

这段代码展示了完整的正则表达式替换过程,并给出了一个只在字符串中保留字母、数字和空格的正则表达式示例——用一个空字符串替换所有其他字符:

//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;

这是从用户给出的字符串中删除标点符号的简单代码

导入所需的库

    import string

以字符串格式询问用户输入

    strs = str(input('Enter your string:'))


for c in string.punctuation:
strs= strs.replace(c,"")
print(f"\n Your String without punctuation:{strs}")