109

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#

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Bruno
  • 1,091
  • 2
  • 7
  • 3
  • @nihcap - Actually, C# doesn't have its own regex flavor, it is a part of the .Net common library. In this case, .Net and C# are both useful tags. – Kobi Apr 10 '11 at 08:55

2 Answers2

185

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

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • What do you mean by "short for" in your last sentence? What would the entire regular expression look like without this shorthand? – Lonnie Best Oct 16 '15 at 07:54
  • 7
    @LonnieBest in regular expressions, for escaped sequences such as \w, it's often a convention that the uppercase escape sequence is the inverse character set of the lowercase escape sequences. E.g. \d is inverse of \D, \s is inverse of \S, \w is inverse of \W, etc. And also, within a character class set delimited by [ ] such as [abc], it's possible to specify an inverse using [^abc]. Thus, \S is equivalent to [^\s], which would also be equivalent to the not-allowed notation [^^\S], if it were allowed. (^^ is not a valid way of representing an inverse of an inverse.) – Dejay Clayton Mar 19 '16 at 03:56
  • @DejayClayton Thanks, I didn't know that. – Lonnie Best Mar 23 '16 at 16:42
  • This answer worked, but why does `\s{2,}` grab newlines proceeding it? If it was `\n\s{2,}` I'd understand. And why does typing a literal space in brackets work? – Modular Mar 28 '20 at 01:57
  • "This answer worked, but why does \s{2,} grab newlines proceeding it?" because `\s` matches spaces, tabs and line breaks. "And why does typing a literal space in brackets work?", well, err, because it does. Don't know what else to say about that :) – Bart Kiers Mar 28 '20 at 09:55
3

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.

Johan
  • 31
  • 1