Reputation: 3459
I have the following code to validate usernames for an application:
Regex usernameRegex = new Regex("[A-Za-z0-9_]");
if (usernameRegex.IsMatch(MyTextBox.Text)) {
// Create account, etc.
}
How would I modify my regular expression to check if the username has a certain number of characters?
Upvotes: 0
Views: 3109
Reputation: 3440
This expression validates only all text which contains any combination of A to Z
, a to z
and number 0 to 9
. You can define the length of the string using the regex:
Regex reg= new Regex(@"^[A-Z]{3,}[a-z]{2,}\d*$")
{3,}
and {2,}
mean here that the string must have at least 3 capital characters, at least 2 small characters, and any amount of digit characters.
For example : Valid : AAAbb, AAAbb2, AAAAAAbbbbb, AAAAAbbbbbb4343434
Invalid: AAb, Abb, AbAbabA, 1AAAbb,
Upvotes: 1
Reputation: 22749
[A-Za-z0-9_]
[] "brackets":
are a group of characters you want to match.
A-Z:
means it will match any alphabet capitalized within this range A-Z.
a-z:
means it will match any small alphabet within this range a-z.
0-9:
means it will match any digit in this range 0-9.
_:
means it will match the "_" character.
now this regex will usually match the following: any character from a to z (small, capital), any number (from 0-9) and the underscore "_".
i.e. "a.,.B.,10.._" this will match "a, B, 10, _". but of course you need to add the singleline regex option.
Upvotes: 0
Reputation: 91525
To set a minimum (or maximum) range in a regular expression you can use the {from,to}
syntax.
The following will only match a string with a minimum of 5 alpha numeric and underscore characters:
[A-Za-z0-9_]{5,}
And the following will match a minimum of 5 and maximum of 10:
[A-Za-z0-9_]{5,10}
Upvotes: 0