Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match more than 2 white spaces but not new line

I want to replace all more than 2 white spaces in a string but not new lines, I have this regex: \s{2,} but it is also matching new lines.

How can I match 2 or more white spaces only and not new lines?

I'm using c#

like image 470
Bruno Avatar asked Apr 10 '11 06:04

Bruno


People also ask

What does \d mean in regex?

In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart. \d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.

What is the regex for white space?

The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.

What is S+ in regex?

The plus sign + is a greedy quantifier, which means one or more times. For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.


1 Answers

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]).

like image 174
Bart Kiers Avatar answered Sep 23 '22 06:09

Bart Kiers