问题
This is the code I am trying:
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();
}
It's accepting aaaaaaaa, but I want a combination of both alpha and numbers like aaaa1234.
回答1:
To require both a letter and a digit to appear in the input, you need positive lookaheads:
@"^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]*$"
^^^^^^^^^^^^^^^^^^^^^^^^
See the regex demo
The (?=.*[a-zA-Z]) makes sure there is a letter and (?=.*[0-9]) makes sure there is a digit in the input string.
Since you are taking the input from a single-line text box, it is safe to use . in the lookahead. As an alternative, you can use @"^(?=[^a-zA-Z]*[a-zA-Z])(?=[^0-9]*[0-9])[a-zA-Z0-9]*$" (based on the principle of contrast).
回答2:
You can use a lookahead to check for a digit and match an alpha before the rest.
^(?i)(?=\D*\d)\d*[A-Z][A-Z\d]*$
^start of string(?i)flag for caseless matching(?=\D*\d)loook ahead for\D*any amount of non-digits followed by\ddigit- if succeeds match
\d*[A-Z]any amount of digits followed by alpha [A-Z\d]*match any amount of alphanumeric characters until$end of string
See demo at regex101
来源:https://stackoverflow.com/questions/35380322/regex-for-alphanumeric-only-is-not-working