C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: This will match newlines, carriage returns, spaces and tabs. We then replace this pattern with a single space.
Result: You can see that the output values only have one space in between the words.
Note: Sometimes, after processing text with other regular expressions and methods, multiple spaces will appear.
Tip: CollapseSpaces() can solve that problem but results in even more complexity in the program.
C# program that uses Regex.Replace on spaces
using System;
using System.Text.RegularExpressions;
class Program
{
static string CollapseSpaces(string value)
{
return Regex.Replace(value, @"\s+", " ");
}
static void Main()
{
string value = "Dot Net Perls";
Console.WriteLine(CollapseSpaces(value));
value = "Dot Net\r\nPerls";
Console.WriteLine(CollapseSpaces(value));
}
}
Output
The Dev Codes
The Dev Codes
Then: You can use the string constructor to convert the character array back to a string.
String Constructor