简体   繁体   English

使用正则表达式检查最少数量的字符?

[英]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 .此表达式仅验证包含A to Za to z和数字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. {3,}{2,}在这里表示字符串必须至少有 3 个大写字符、至少 2 个小字符和任意数量的数字字符。

For example : Valid : AAAbb, AAAbb2, AAAAAAbbbbb, AAAAAbbbbbb4343434例如:有效:AAAbb、AAAbb2、AAAAAAbbbbb、AAAAAbbbbbb4343434

Invalid: AAb, Abb, AbAbabA, 1AAAbb,无效:AAb、Abb、AbAbabA、1AAAbb、

To set a minimum (or maximum) range in a regular expression you can use the {from,to} syntax.要在正则表达式中设置最小(或最大)范围,您可以使用{from,to}语法。

The following will only match a string with a minimum of 5 alpha numeric and underscore characters:以下仅匹配至少包含 5 个字母数字和下划线字符的字符串:

[A-Za-z0-9_]{5,}

And the following will match a minimum of 5 and maximum of 10:以下将匹配最少 5 个和最多 10 个:

[A-Za-z0-9_]{5,10}
[A-Za-z0-9_]

[] "brackets": are a group of characters you want to match. [] "brackets":是一组要匹配的字符。

AZ: means it will match any alphabet capitalized within this range AZ. AZ:表示匹配这个范围内的任何大写字母。

az: means it will match any small alphabet within this range az. az:表示匹配az范围内的任何小字母。

0-9: means it will match any digit in this range 0-9. 0-9:表示将匹配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 "_".现在这个正则表达式通常会匹配以下内容:从 a 到 z(小,大写)的任何字符、任何数字(从 0 到 9)和下划线“_”。

ie "a.,.B.,10.._" this will match "a, B, 10, _".即 "a.,.B.,10.._" 这将匹配 "a, B, 10, _"。 but of course you need to add the singleline regex option.但当然你需要添加单行正则表达式选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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