Reputation: 4246
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]+");
^
: Begin of a line / starts with[A-Z0-9]
: contains a character in upper cases, or numbers[\S]
: Doesn't contains a spacing character+
: May contains one or more occurence of the patternI 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
AA AA
is not valid because it contains a spacing characteraaaa
is not valid because it doesn't contains at least uppercase or numberHELLOWORLD
is valid because it contains only uppercaseHELLO654
is valid because it contains only uppercase or numbersUpvotes: 2
Views: 2668
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