How to remove control characters except new line? (C#)

Viewed 513

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)

2 Answers

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)

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