C#正则表达式-删除多余的空格,但保留新行 [英] C# Regex - Remove extra whitespaces but keep new lines
问题描述
我正在使用此正则表达式:
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 ?
推荐答案
在空白类中排除CRLF的[^\S\r\n]+
.
[^]
是否定类. \S
是一个否定类,等于不 [ space, tab, ff, lf, cr ]
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.
不是非空格= [^\S]
= [\s]
Not Not whitespace = [^\S]
= [\s]
但是,否定条件适用于下一个课目以及下一个课目
However, the negative condition applies to the next class item as well as the next ...
因此,既然已包含空格,则可以从类中排除特定的空格项.
[^\S\r\n]
表示除CR或LF之外的所有空白.
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.
这篇关于C#正则表达式-删除多余的空格,但保留新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!