这是我正在尝试的代码:
string MatchNumberPattern = "^[a-zA-Z0-9]*$";
if (!Regex.IsMatch(cueTextBox9.Text, MatchNumberPattern))
{
MessageBox.Show("Enter 8 Space Alphanumeric BT ID only");
cueTextBox9.Text = String.Empty;
}
else
{
do something();
}
它正在接受aaaaaaaa
,但我希望结合使用alpha和数字aaaa1234
。
答案 0 :(得分:2)
要求输入中显示字母和数字,您需要正向前瞻:
@"^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]*$"
^^^^^^^^^^^^^^^^^^^^^^^^
请参阅regex demo
(?=.*[a-zA-Z])
确保有一个字母,(?=.*[0-9])
确保输入字符串中有一个数字。
由于您从单行文本框中获取输入,因此在前瞻中使用.
是安全的。作为替代方案,您可以使用@"^(?=[^a-zA-Z]*[a-zA-Z])(?=[^0-9]*[0-9])[a-zA-Z0-9]*$"
(基于对比原理)。
答案 1 :(得分:2)
您可以使用lookahead检查数字并在其他数据之前匹配alpha。
^(?i)(?=\D*\d)\d*[A-Z][A-Z\d]*$
^
字符串开头(?i)
flag用于无壳匹配(?=\D*\d)
提前\D*
任意数量的非数字,然后是\d
数字\d*[A-Z]
任意数量的数字后跟alpha [A-Z\d]*
匹配任意数量的字母数字字符,直到$
字符串结尾答案 2 :(得分:0)
async Task<string> CheckPasswordAgainstPasswordSettings(string password)
{
Regex rxUpper= new Regex(@"[A-Z]");
Regex rxLower = new Regex(@"[a-z]");
var passwordcomplexityrulesetttings= (await _PasswordComplexityRuleService.All()).First();
if(passwordcomplexityrulesetttings==null)
{
return "password valid";
}
if(passwordcomplexityrulesetttings.MinLength> password.Length)
{
return "password is not of minimum length";
}
if (passwordcomplexityrulesetttings.MustContainLettersNumbers)
{
if(password.Any(a=>!char.IsDigit(a)&&!char.IsLetter(a)) && !passwordcomplexityrulesetttings.MustContainSpecialCharacters)
{
return "password must contain letters and numbers";
}
}
if (passwordcomplexityrulesetttings.MustContainSpecialCharacters)
{
if (!password.Any(a => !char.IsDigit(a) && !char.IsLetter(a)))
{
return "password must contain special characters";
}
}
if (passwordcomplexityrulesetttings.MustContainUpperLower)
{
if (!rxLower.Match(password).Success||!rxUpper.Match(password).Success)
{
return "password must contain upper and lower case";
}
}
return "password valid";
}