简体   繁体   中英

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);
}

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 :)

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

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

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)))

All of the above:

or

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

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);  

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]", "");   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM