Loading ...

Regex: Replace multiple spaces with a single space | CodeAsp.Net

Regex: Replace multiple spaces with a single space

 /5
0 (0votes)

In this blog I will show how to replace multiple spaces with a single space with REGEX. Let's say we have a string "a  b   c    d  e      f  g" and we want to replace multiple spaces with a single space so that the output comes "a b c d e f g". Below is the sample code to do the same:

using System;
using System.Text.RegularExpressions;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            const string inputString = "a  b   c    d  e      f  g";
            string output = Regex.Replace(inputString, @"\s+", " ");

            Console.WriteLine(output);
            Console.ReadLine();
        }
    }
}

Output:

Below is the explanation of regex:

\s+

Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\s+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»


Created with RegexBuddy

Comments (no comments yet)

Top Posts