Anwar
Anwar

Reputation: 4246

Check for white space Regex C#

I created a Regex to match the following rule :

Must contains only upper case and numbers. Must not contains any other charaters including spacing characters (\n, \t, \v, \r, ...).

So I created the following rule :

Regex rule = new Regex(@"^[A-Z0-9\S]+");

I put a @ character to be able to use escape character \S.

To verify it, I created a simple WebForm, with a asp:TextBox, and a valid asp:Button to check if it is correct :

myFile.aspx

<asp:TextBox runat="server" ID="textBox_1"></asp:TextBox>
<asp:Button runat="server" ID="button_1" Text="Check" OnClick="button_1_Click"/>

Then I binded the click to check if the rule is verifyied :

myFile.aspx.cs

protected void button_1_Click(object sender, EventArgs e)
{

    string textbox = textBox_1.Text;
    Regex rule = new Regex(@"^[A-Z0-9\S]+");            

    if (rule.IsMatch(textbox))
    {
        /* Match */
    }
    else
    {
        /* Doesn't match */
    }            
}

My problem :

When I enter the string AA AA, the rule is checked, which is not what I want. Did I wrote wrong my rule ?

To check the rule

Upvotes: 2

Views: 2668

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

You probably want to anchor the regex at the end as well. Also you don't need the \S portion because [A-Z0-9] can't include any space characters anyway.

^[A-Z0-9]+$

Your current regex doesn't force the match to occur at the end of a string, and so AAA AAA passes. Specifically, the first AAA passes and the rest of the string isn't required to meet your requirements.

Upvotes: 3

Related Questions