How can you strip non-ASCII characters from a string? (in C#)

前端 未结 11 1042
迷失自我
迷失自我 2020-11-22 17:24

How can you strip non-ASCII characters from a string? (in C#)

相关标签:
11条回答
  • 2020-11-22 17:40

    I found the following slightly altered range useful for parsing comment blocks out of a database, this means that you won't have to contend with tab and escape characters which would cause a CSV field to become upset.

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

    If you want to avoid other special characters or particular punctuation check the ascii table

    0 讨论(0)
  • 2020-11-22 17:43

    I use this regular expression to filter out bad characters in a filename.

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

    That should be all the characters allowed for filenames.

    0 讨论(0)
  • 2020-11-22 17:47

    Inspired by philcruz's Regular Expression solution, I've made a pure LINQ solution

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

    This is untested code.

    0 讨论(0)
  • 2020-11-22 17:51

    Here is a pure .NET solution that doesn't use regular expressions:

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

    It may look cumbersome, but it should be intuitive. It uses the .NET ASCII encoding to convert a string. UTF8 is used during the conversion because it can represent any of the original characters. It uses an EncoderReplacementFallback to to convert any non-ASCII character to an empty string.

    0 讨论(0)
  • 2020-11-22 17:53

    no need for regex. just use encoding...

    sOutput = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(sInput));
    
    0 讨论(0)
提交回复
热议问题