'Remove extra whitespaces, but keep new lines using a regular expression in C# [duplicate]
I am using this regular expression,
Regex.Replace(value.Trim(), @"\s+", " ");
To trim and minimize extra spaces into one space.
The problem is that it also removes new lines from the text.
How can I fix the regex so that it will keep the new lines?
Solution 1:[1]
I haven't managed to test it in C# yet, but the following works on http://www.regexr.com/:
Regex.Replace(value.Trim(), @"[^\S\r\n]+", " ");
Credit goes to Match whitespace but not newlines
The Regex works by matching the negated character class of not-whitespace or return / newlines.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
