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


当前回答

我使用这个正则表达式来过滤掉文件名中的坏字符。

Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")

这应该是文件名所允许的所有字符。

其他回答

我使用这个正则表达式来过滤掉文件名中的坏字符。

Regex.Replace(directory, "[^a-zA-Z0-9\\:_\- ]", "")

这应该是文件名所允许的所有字符。

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

这是未经测试的代码。

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

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

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

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

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

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