Search code examples
c#regexnon-ascii-characters

How to remove space, comma or similar non-ASCI character in c#?


I want to remove space, commas or similar non-ASCI characters from the string but I didn't.

I tried these but doesn't work.

 // my string value = request.ReportName
    Regex.Replace(request.ReportName, @"[^\u0000-\u007F]+", string.Empty);
    Regex.Replace(request.ReportName, @"[^\uxxxx\u0000-\u007F]", string.Empty),

By the way I tried this as well but doesn't work as well.

System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(request.ReportName));

For example: request.ReportName = "CAption, For long Text double length long to keep"

I want to do this: CAptionForlongTextdoublelengthlongtokeep. What can I do? Any idea, please?


Solution

  • You can use a regular expression to replace all non-letters:

    Regex.Replace(request.ReportName, @"[^A-Za-z]+", String.Empty);
    

    Another idea for doing the same thing would be

    Regex MyRegex = new Regex("[^A-Za-z]", RegexOptions.IgnoreCase);
    string s = MyRegex.Replace(request.ReportName, @"");
    

    This might also help you

    new String(request.ReportName.Where(c => Char.IsLetter(c) && Char.IsUpper(c)).ToArray());