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

C#.NetRegexNewlineWhitespace

C# Problem Overview


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#

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrunoView Question on Stackoverflow
Solution 1 - C#Bart KiersView Answer on Stackoverflow
Solution 2 - C#JohanView Answer on Stackoverflow