仅用于字母数字的正则表达式不起作用 [英] regex for alphanumeric only is not working

查看:25
本文介绍了仅用于字母数字的正则表达式不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在尝试的代码:

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();
}

它接受aaaaaaaa,但我想要字母和数字的组合,例如aaaa1234.

It's accepting aaaaaaaa, but I want a combination of both alpha and numbers like aaaa1234.

推荐答案

要要求输入中同时出现字母和数字,您需要正向预测:

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]*$"
    ^^^^^^^^^^^^^^^^^^^^^^^^

查看正则表达式演示

(?=.*[a-zA-Z]) 确保有一个字母,(?=.*[0-9]) 使得确保输入字符串中有一个数字.

The (?=.*[a-zA-Z]) makes sure there is a letter and (?=.*[0-9]) makes sure there is a digit in the input string.

由于您从单行文本框中获取输入,因此在前瞻中使用 . 是安全的.作为替代方案,您可以使用 @"^(?=[^a-zA-Z]*[a-zA-Z])(?=[^0-9]*[0-9])[a-zA-Z0-9]*$"(基于对比原理).

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).

这篇关于仅用于字母数字的正则表达式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆