Joseph Anderson
Joseph Anderson

Reputation: 4144

C# RegEx Keep Line Breaks

I need to remove all special characters except line breaks. Does anyone know of a RegEx that would accomplish this task? Here is my RegEx:

        string b = "ABC\r\nVVV";
        string a = Regex.Replace(b, "[^\\x20-\\x7E]", "");

Upvotes: 1

Views: 296

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You match any char other than a char from space to tilde with "[^\\x20-\\x7E]". So, it matches CR and LF symbols. To avoid matching those chars, add them to the character class, and it is best to add + after the ] to match 1 or more occurrences to remove whole sequences at once:

string a = Regex.Replace(b, "[^\\x20-\\x7E\r\n]+", "");

See the regex demo at RegexStorm.

Upvotes: 2

Related Questions