Remove extra space from a string using Regex in C#

Remove extra space from a string using Regex in C#

Regex:

It represents an immutable regular expression. Regex is referenced with System.Text class

Problem statement:

A string which has multiple white space in between, simple trim or replace does not help here. What is the solution?

Solution:

public static string TrimExtraSpace(string textToTrim)
{
	if(!string.IsNullOrEmpty(textToTrim))
	{
		Regex trimmer = new Regex(@"\s\s+");
		return trimmer.Replace(textToTrim.Trim(), "");
	}
	else
	{
		return string.Empty;
	}
}

If you call above method and pass a string having multiple white space between, it will remove additional space and returns a running string back.

Hope it helps!!!

Leave a Reply

Your email address will not be published. Required fields are marked *