C# Regex – How to Replace All White Space with a Single Space

c++regexwhitespace

My program is a file validation utility. I have to read in a format file and then parse out each line by a single space. But obviously, the person who wrote the format file may use tabs, or two spaces, or any form of whitespace, and I'm looking for some code to do that. I've tried this:

public static string RemoveWhitespace(this string line)
{
    try
    {
        return new Regex(@"\s*").Replace(line, " ");
    }
    catch (Exception)
    {
        return line;
    }
}

I'm assuming this is wrong. What should I do?

Best Answer

You can do this -

System.Text.RegularExpressions.Regex.Replace(str,@"\s+"," ");

where str is your string.