Remove extra spaces from string using regular expression, asp.net, c#





Removes extra space from the string using Regular expression.

public static readonly RegexOptions Options =          RegexOptions.IgnorePatternWhitespace |
RegexOptions.Singleline;
public string RemoveExtaSpaces(string text)
{
Regex regex = new Regex(@”\s{2,}”, Options);
text = regex.Replace(text.Trim(), ” “); //This line removes extra spaces and make space exactly one.
//To remove the  space between the end of a word and a punctuation mark used in the text we will
//be using following line of code

regex=new Regex(@”\s(\!|\.|\?|\;|\,|\:)”); // “\s” whill check for space near all puntuation marks in side ( \!|\.|\?|\;|\,|\:)”); )
text = regex.Replace(text, “$1”);
return text;

}

Above function removes all extra spaces in the string to make one space exactly. Feel free to use, its been used and tested

static void Main(string[] args)

{

string mytext = “blah    blah    blah   blah   .”;

Console.WriteLine(mytext);

Console.WriteLine(RemoveExtaSpaces(mytext));

}

Result

blah blah blah blah.




Tags: , , , ,

5 Responses to “Remove extra spaces from string using regular expression, asp.net, c#”

  1. Thanks for the expression. Very useful, in deed!

  2. Pepe says:

    Very useful

  3. vikas says:

    this solution removes only one space (for ex: “blah .” will be replaced with “blah .” – and not “blah.” )
    How do i replace any number or spaces between punctuation and/or words (for ex: “blah blah blah” should be replaced with “blah blah blah”

    thanks in adv.

  4. Naveed says:

    Vikas check the result and input string. It does what you asking for.

  5. PCR says:

    Thanks a lot its really working fine