简体   繁体   中英

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]", "");

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM