简体   繁体   中英

Using regular expressions to check for a minimum number of characters?

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?

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,

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}
[A-Za-z0-9_]

[] "brackets": are a group of characters you want to match.

AZ: means it will match any alphabet capitalized within this range AZ.

az: means it will match any small alphabet within this range az.

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 "_".

ie "a.,.B.,10.._" this will match "a, B, 10, _". but of course you need to add the singleline regex option.

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