2

I want to remove any invisible chars from a string, only keep spaces & any chars from 0x20-0x7F, I use this: Regex.Replace(QueryString, @"[^\s\x20-\x7F]", ""); However it does not work

QueryString has a char 0xA0, after that, the char still exists in QueryString.

I am not sure why this failed to work?

susu
  • 73
  • 1
  • 5

2 Answers2

3

0xA0 is the non-breaking space character - and as such it's matched with \s. Rather than using \s, expand this out into the list of whitespace characters you want to include.

Will A
  • 24,780
  • 5
  • 50
  • 61
0

I think you would rather use StringBuilder to process such strings.

StringBuilder sb = new StringBuilder(str.Length);
foreach(char ch in str)
{
    if (0x20 <= ch && ch <= 0x7F)
    {
        sb.Append(ch)
    }
}

string result = sb.ToString();
oxilumin
  • 4,775
  • 2
  • 18
  • 25