regex for alphanumeric only is not working

元气小坏坏 提交于 2021-01-28 19:30:15

问题


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 \d digit
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!