如何从字符串中删除非ASCII字符? (在C#中)
string s = "søme string";
s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);
我使用了这个正则表达式:
string s = "søme string";
Regex regex = new Regex(@"[^a-zA-Z0-9\s]", (RegexOptions)0);
return regex.Replace(s, "");
我使用这个正则表达式来过滤掉文件名中的错误字符。
Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")
这应该是文件名允许的所有字符。
这是一个不使用正则表达式的纯.NET解决方案:
string inputString = "Räksmörgås";
string asAscii = Encoding.ASCII.GetString(
Encoding.Convert(
Encoding.UTF8,
Encoding.GetEncoding(
Encoding.ASCII.EncodingName,
new EncoderReplacementFallback(string.Empty),
new DecoderExceptionFallback()
),
Encoding.UTF8.GetBytes(inputString)
)
);
它可能看起来很麻烦,但它应该是直观的。它使用.NET ASCII编码转换字符串。转换期间使用UTF8,因为它可以表示任何原始字符。它使用EncoderReplacementFallback将任何非ASCII字符转换为空字符串。
我相信MonsCamus意味着:
parsememo = Regex.Replace(parsememo, @"[^\u0020-\u007E]", string.Empty);
如果你不想剥离,但实际上将拉丁语重音为非重音字符,请看看这个问题:How do I translate 8bit characters into 7bit characters? (i.e. Ü to U)
受philcruz's Regular Expression solution的启发,我制作了纯粹的LINQ解决方案
public static string PureAscii(this string source, char nil = ' ')
{
var min = '\u0000';
var max = '\u007F';
return source.Select(c => c < min ? nil : c > max ? nil : c).ToText();
}
public static string ToText(this IEnumerable<char> source)
{
var buffer = new StringBuilder();
foreach (var c in source)
buffer.Append(c);
return buffer.ToString();
}
这是未经测试的代码。
不需要正则表达式。只是使用编码...
sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));
我发现以下稍微改变的范围对于解析数据库中的注释块非常有用,这意味着您不必与tab和转义字符竞争,这会导致CSV字段变得烦乱。
parsememo = Regex.Replace(parsememo, @"[^\u001F-\u007F]", string.Empty);
如果你想避免其他特殊字符或特殊标点符号检查the ascii table
我来到这里寻找扩展的ascii字符的解决方案,但无法找到它。我找到的最接近的是bzlm's solution。但这仅适用于高达127的ASCII码(显然你可以在他的代码中替换编码类型,但我认为理解它有点复杂。因此,共享此版本)。这是一个适用于extended ASCII codes i.e. upto 255的解决方案,即ISO 8859-1
它找到并删除非ascii字符(大于255)
Dim str1 as String= "â, ??î or ôu🕧� n☁i✑💴++$-💯♓!🇪🚑🌚‼⁉4⃣od;/⏬'®;😁☕😁:☝)😁😁///😍1!@#"
Dim extendedAscii As Encoding = Encoding.GetEncoding("ISO-8859-1",
New EncoderReplacementFallback(String.empty),
New DecoderReplacementFallback())
Dim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)
Dim str2 As String = extendedAscii.GetString(extendedAsciiBytes)
console.WriteLine(str2)
'Output : â, ??î or ôu ni++$-!‼⁉4od;/';:)///1!@#$%^yz:
这是一个working fiddle for the code
根据要求替换编码,其余应保持不变。
这不是最佳的性能,而是一种非常简单的Linq方法:
string strippedString = new string(
yourString.Where(c => c <= sbyte.MaxValue).ToArray()
);
缺点是所有“幸存”字符首先被放入char[]
类型的数组中,然后在string
构造函数不再使用它之后丢弃。