检查给定密码在C#中是否包含至少一个数字和一个字母的正则表达式? [英] Regular expression to check if a given password contains at least one number and one letter in c#?

查看:905
本文介绍了检查给定密码在C#中是否包含至少一个数字和一个字母的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我写一个正则表达式来检查密码中是否包含至少一个字母和一个数字吗?

Can anyone help me write a regular expression for checking if a password has at least one letter and one number in it?

我有一个要求用户密码必须是字母数字,我希望能够使用正则表达式进行检查。

I have a requirement that users passwords must be alphanumeric and I want to be able to check for that using a regular expression.

推荐答案

正向超前是您想要的。正则表达式如下所示:

Positive lookahead is what you're looking for. The regex looks like this:

(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+

此处,(?=。* [A-Za-z])是肯定的前瞻,它断言您的字符串为至少一个字符 (?=。* [0-9])断言它至少有个数字。请务必注意,正向搜索不会返回匹配项,而是断言是否存在匹配项。因此,您应该将前一个正则表达式读为断言它至少有一个字符;断言它至少有一个数字;现在我们知道断言已经通过,只需检查字母数字字符即可。

Here, (?=.*[A-Za-z]) is the positive lookahead which asserts that your string as at least one character, and (?=.*[0-9]) asserts that it has at least one digit. It's important to note that the positive lookahead doesn't return a match, but rather asserts whether a match exists or not. So, you should read the previous regex as "assert that it has at least one character; assert it has at least one digit; now that we know the assertions have passed, just check for alphanumeric characters".

这很有趣,因为它使您可以轻松组合应用程序的验证要求,而不必使正则表达式非常复杂。例如,如果您现在要求字符串具有恰好 20个字符,则只需添加一个新的正向超前断言,如下所示:

This is very interesting because it allows you to easily combine the validation requirements of your application, without making your regex very complex. For example, if you now require the string to have exactly 20 characters, you just need to add a new positive lookahead assertion, like so:

(?=[A-Za-z0-9]{20})(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+

希望它会有所帮助!

这篇关于检查给定密码在C#中是否包含至少一个数字和一个字母的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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