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#
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] ).
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.
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.
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.
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]
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With