Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

replace

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)

like image 580
Developer505 Avatar asked Aug 31 '25 20:08

Developer505


1 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)
like image 123
The fourth bird Avatar answered Sep 03 '25 11:09

The fourth bird