对于这个问题的30秒内希望得到答案,我特意寻找C#
但在一般情况下,删除任何语言标点符号的最佳方法是什么?
我应补充一点:理想情况下,解决方案不需要您枚举所有可能的标点符号.
GWL*_*osa 103
new string(myCharCollection.Where(c => !char.IsPunctuation(c)).ToArray());
Run Code Online (Sandbox Code Playgroud)
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的算法,这是发布的最佳表现.
您可以使用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)
这应该找到任何标点符号.
这个帖子太旧了,但我不能发布更优雅的(IMO)解决方案.
string inputSansPunc = input.Where(c => !char.IsPunctuation(c)).Aggregate("", (current, c) => current + c);
Run Code Online (Sandbox Code Playgroud)
这是LINQ没有WTF.