Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to replace all white space with a single space

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?

like image 435
New Start Avatar asked Sep 16 '10 09:09

New Start


People also ask

How do I replace multiple spaces with single space in bash?

Continuing with that same thought, if your string with spaces is already stored in a variable, you can simply use echo unquoted within command substitution to have bash remove the additional whitespace for your, e.g. $ foo="too many spaces."; bar=$(echo $foo); echo "$bar" too many spaces.


1 Answers

You can do this -

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

where str is your string.

like image 169
Sachin Shanbhag Avatar answered Oct 16 '22 06:10

Sachin Shanbhag