C# Regex - Remove extra whitespaces but keep new lines [duplicate]

廉价感情. 提交于 2019-12-21 01:20:49

问题


I am using this regex :

Regex.Replace(value.Trim(), @"\s+", " ");

To trim and minimize extra spaces into one space.
The problem is that it also removes new lines from the text.

How can I fix the regex so that it will keep the new lines ?


回答1:


Exclude CRLF's [^\S\r\n]+ within the whitespace class.
[^] is a negative class. \S is a negative class which equals not [ space, tab, ff, lf, cr ]

The thing about negative classes is it factored out of the group and applies to each member
in the group separately. And like math two negative equal a positive.

Not Not whitespace = [^\S] = [\s]

However, the negative condition applies to the next class item as well as the next ...

So, now that whitespace is included, you can exclude particular whitespace items from the class.
[^\S\r\n] means all whitespace except CR or LF.




回答2:


Haven't managed to test it in C# yet, but the following works on http://www.regexr.com/:

Regex.Replace(value.Trim(), @"[^\S\r\n]+", " ");

Credit goes to Match whitespace but not newlines

The Regex works by matching the negated character class of not-whitespace or return / newlines.



来源:https://stackoverflow.com/questions/25954446/c-sharp-regex-remove-extra-whitespaces-but-keep-new-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!