正则表达式匹配2个以上的空白,但不匹配新行

我想在一个字符串中替换所有2个以上的空格,但不是新行,我有这个 regex: \s{2,},但它也匹配新行。

如何才能只匹配2个或多个空白,而不匹配新行?

我用 c #

107685 次浏览

Put the white space chars you want to match inside a character class. For example:

[ \t]{2,}

matches 2 or more spaces or tabs.

You could also do:

[^\S\r\n]{2,}

which matches any white-space char except \r and \n at least twice (note that the capital S in \S is short for [^\s]).

Regex to target only two spaces: [ ]{2,} Brackets in regex is character class. Meaning just the chars in there. Here just space. The following curly bracket means two or more times.