如何从字符串中剥离非ascii字符?(c#)


当前回答

如果你想要一个只有ISO-8859-1字符并且排除非标准字符的字符串,你应该使用这个表达式:

var result = Regex.Replace(value, @"[^\u0020-\u007E\u00A0-\u00FF]+", string.Empty);

注意:使用Encoding.GetEncoding("ISO-8859-1")方法将不能完成这项工作,因为未定义的字符不会被排除在外。

.Net小提琴样本

维基百科ISO-8859-1代码页获取更多详细信息。

其他回答

我发现下面稍微改变的范围对于从数据库中解析注释块很有用,这意味着您不必与制表符和转义字符相争斗,这将导致CSV字段变得混乱。

parsememo = Regex.Replace(parsememo, @"[^\u001F-\u007F]", string.Empty);

如果您希望避免使用其他特殊字符或特殊标点符号,请检查ascii表

受philcruz的正则表达式解决方案的启发,我做了一个纯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();
}

这是未经测试的代码。

public string ReturnCleanASCII(string s)
    {
        StringBuilder sb = new StringBuilder(s.Length);
        foreach (char c in s)
        {
            if ((int)c > 127) // you probably don't want 127 either
                continue;
            if ((int)c < 32)  // I bet you don't want control characters 
                continue;
            if (c == '%')
                continue;
            if (c == '?')
                continue;
            sb.Append(c);
        }
        return sb.ToString();
    }

不需要正则表达式。只要使用编码…

sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));

如果你不想剥离,而是真正地将拉丁重音字符转换为非重音字符,看看这个问题:我如何将8位字符转换为7位字符?(即Ü到U)