3

I'm using this code to remove unprintable characters from the string but I don't want to remove new line characters (\n) from the string. Here's the code I use for now.

Regex.Replace(value, @"\p{C}+", string.Empty)

I don't know about Regex. I found this code on the Internet. It works but it removes new line control characters too. I was wondering how I can do what I want. (Regex is not compulsory)

  • The regex is a good solution, with a regex you can set a filter (pattern) on your string input, the above filter is not complete and you should choose another pattern. however, if you are not familiar with regex you can do this without regex; so, check this link, it might be useful: https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string#answer-55896169 but it is good for you to learn about Regular Expressions (Regex) – S.A.Parkhid Oct 15 '20 at 21:39

2 Answers2

6

You might use a negated character class [^ excluding matching a newline and use \P{C} to match to opposite of \p{C}

[^\P{C}\n]+

.NET regex demo (Click on the Context tab)

For example

Regex.Replace(value, @"[^\P{C}\n]+", string.Empty)
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Do something like this, adding whatever other control characters you want between the square brackets.

Regex.Replace(value, @"[\t\0\b\a\v\f]+", String.Empty)
Colin
  • 4,025
  • 21
  • 40