Steve Wood
Steve Wood

Reputation: 51

Why isn't my regex removing the whitespace?

I'm using the code below to determine if the value entered into textBoxAddress.Text is a number (fax number) or an email address. My isNumber test below won't work if the fax number has spaces so I'm trying to remove all white space with the Regex, the whitespace isn't being removed. Can you spot my problem?

Thank you.

    string faxOrEmail = textBoxAddress.Text;
    faxOrEmail = Regex.Replace(faxOrEmail, @"\s+", " ");  //<---Regex
    bool testForFax = IsNumber(faxOrEmail);

    if (testForFax == true)
    {
        //send fax
        MessageBox.Show(faxOrEmail);
    }
    else
    {
        backgroundWorker1.RunWorkerAsync(); //Send Email  
    }

static bool IsNumber(string value)
{
    // Return true if this is a number.
    int number1;
    return int.TryParse(value, out number1);
}

Upvotes: 1

Views: 128

Answers (6)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

If faxOrEmail only contains spaces (" ") and no tabs for instance, then you can go with:

faxOrEmail = faxOrEmail.Replace(" ", ""); 

On the other hand, you could also remove everything (including dashes, slashes, parentheses, etc.) but decimal digits with Regex:

faxOrEmail = Regex.Replace(faxOrEmail, "[^0-9]", "");   

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12458

If you want to replace 2 or more consecutive spaces with one space, then do this:

faxOrEmail = Regex.Replace(faxOrEmail, @"\s{2,}", " ");  

If you want to remove all spaces, then do this:

faxOrEmail = Regex.Replace(faxOrEmail, @"\s+", string.Empty);  

Upvotes: 0

Mnescat
Mnescat

Reputation: 193

All of the above:

or

Don't use a regular expression at all. Just use the Replace method and replace " " with ""

Upvotes: 0

user1228
user1228

Reputation:

You are replacing one or more spaces with a single space.

Regex.Replace(faxOrEmail, @"\s+", string.Empty);

This doesn't remove dashes, and your IsNumber method isn't necessary.

string.Join(string.Empty, faxOrEmail.ToCharArray().Where(x=> char.IsNumber(x)))

Upvotes: 1

Ian
Ian

Reputation: 34489

You are replacing the spaces, with spaces! Use String.Empty to avoid these problems:

faxOrEmail = Regex.Replace(faxOrEmail, @"\s+", String.Empty);

Upvotes: 1

piotrekkr
piotrekkr

Reputation: 3181

Try this:

faxOrEmail = Regex.Replace(faxOrEmail, @"\s+", "");

I don't know C# to well but if you want to remove spaces try replacing it with empty string not space :)

Upvotes: 1

Related Questions