检查字符串是否包含数字和字母(至少)

时间:2020-12-19 01:34:08

I wish to check if a password contains at least one letter and a number. special characters are accepted but not required...

我想检查一个密码是否包含至少一个字母和一个数字。特殊字符被接受,但不需要…

That will be a simple password checker.

这将是一个简单的密码检查器。

5 个解决方案

#1


22  

You can use lookahead assertions to check for existence of any digit and any letter as:

您可以使用前视断言检查任何数字和任何字母是否存在:

^(?=.*[a-zA-Z])(?=.*[0-9])

#2


6  

Using a single regex for this can lead to somewhat unreadable/unreliable code. It may make more sense to use simpler regexes eg [0-9] to check for the existence of a digit and break the requirements of your password strength checker into a multi-line if. Also this allows you to know more readily at what stage the validation failed and possibly make suggestions to the user.

为此使用一个regex可能导致某些不可读/不可靠的代码。使用更简单的regexes(如[0-9])检查一个数字的存在性,并将密码强度检查器的要求转换为多行if,可能更有意义。此外,这还允许您更容易地了解验证失败的阶段,并可能向用户提出建议。

#3


1  

([0-9].*[a-zA-Z])\|([a-zA-Z].*[0-9])

Not sure if the pipe needs to be escaped in your regexp environment or not.

不确定管道是否需要在regexp环境中转义。

#4


0  

/.*?(?:[a-z].*?[0-9]|[0-9].*?[a-z]).*?/

(just one possible solution)

(只是一个可能的解决方案)

#5


0  

Simple solution to check for password containing at least one letter, at least one digit and no spaces:

简单的解决方案,检查密码包含至少一个字母,至少一个数字,没有空格:

\S*(\S*([a-zA-Z]\S*[0-9])|([0-9]\S*[a-zA-Z]))\S*

#1


22  

You can use lookahead assertions to check for existence of any digit and any letter as:

您可以使用前视断言检查任何数字和任何字母是否存在:

^(?=.*[a-zA-Z])(?=.*[0-9])

#2


6  

Using a single regex for this can lead to somewhat unreadable/unreliable code. It may make more sense to use simpler regexes eg [0-9] to check for the existence of a digit and break the requirements of your password strength checker into a multi-line if. Also this allows you to know more readily at what stage the validation failed and possibly make suggestions to the user.

为此使用一个regex可能导致某些不可读/不可靠的代码。使用更简单的regexes(如[0-9])检查一个数字的存在性,并将密码强度检查器的要求转换为多行if,可能更有意义。此外,这还允许您更容易地了解验证失败的阶段,并可能向用户提出建议。

#3


1  

([0-9].*[a-zA-Z])\|([a-zA-Z].*[0-9])

Not sure if the pipe needs to be escaped in your regexp environment or not.

不确定管道是否需要在regexp环境中转义。

#4


0  

/.*?(?:[a-z].*?[0-9]|[0-9].*?[a-z]).*?/

(just one possible solution)

(只是一个可能的解决方案)

#5


0  

Simple solution to check for password containing at least one letter, at least one digit and no spaces:

简单的解决方案,检查密码包含至少一个字母,至少一个数字,没有空格:

\S*(\S*([a-zA-Z]\S*[0-9])|([0-9]\S*[a-zA-Z]))\S*