Remove extra spaces from string using regular expression

May 13th, 2009 by dhruval.shah § 0

This is a procedure for removing extra spaces from text and make it exact one.

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” will check for space near all punctuation marks in side ( \!|\.|\?|\;|\,|\:)”); )

text = regex.Replace(text, “$1″);
return text;

}

Tagged:

§ Leave a Reply

What's this?

You are currently reading Remove extra spaces from string using regular expression at Digicorp.

meta

Share