Bash shell 中的正则表达式密码验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20845497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex password validation in Bash shell
提问by Arun Shankar
I am using Regexes in Bash Shell script. I am using the below Regex code to check password criteria : Password should be at least 6 characters long with at least one digit and at least one Upper case Alphabet. I validated in the Regex validation tools, the Regex I have formed works fine. But, it fails in Bash Shell Script. Please provide your thoughts.
我在Bash Shell 脚本中使用正则表达式。我正在使用以下正则表达式代码来检查密码标准:密码长度应至少为 6 个字符,至少有一位数字和至少一个大写字母。我在 Regex 验证工具中进行了验证,我形成的 Regex 工作正常。但是,它在 Bash Shell 脚本中失败。请提供您的想法。
echo "Please enter password for User to be created in OIM: "
echo "******Please Note: Password should be at least 6 characters long with one digit and one Upper case Alphabet******"
read user_passwd
regex="^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)\S{6,}$"
echo $user_passwd
echo $regex
if [[ $user_passwd =~ $regex ]]; then
echolog "Password Matches the criteria"
else
echo "Password criteria: Password should be at least 6 characters long with one digit and one Upper case Alphabet"
echo "Password does not Match the criteria, exiting..."
exit
fi
回答by anubhava
BASH regex engine doesn't support lookarounds as in your regex.
BASH 正则表达式引擎不支持正则表达式中的环视。
You can use following shell glob check to make sure password matches your criteria:
您可以使用以下 shell glob 检查来确保密码符合您的条件:
[[ ${#s} -ge 6 && "$s" == *[A-Z]* && "$s" == *[a-z]* && "$s" == *[0-9]* ]]
It will make sure that input string $smeets all these conditions:
它将确保输入字符串$s满足所有这些条件:
- at least 6 characters long
- has at least one digit
- has at least one Upper case Alphabet
- has at least one Lower case Alphabet
- 至少 6 个字符长
- 至少有一位
- 至少有一个大写字母
- 至少有一个小写字母
回答by dozer
I'm adding to anubhava's answer. His check worked for me but not completely.
For e.g. "hello123" or "HELLO123" also passed the check, so it didn't detect case.
The issue was with the locale settings, more specifically the LC_COLLATEvariable. It needs to be set to "C" to consider case.
But a better solution was to use character classes rather than range expressions.
The explanation herehelped me to solve my problem. Eventually using character classes worked for me.
我正在添加 anubhava 的答案。他的支票对我有用,但并不完全。例如“hello123”或“HELLO123”也通过了检查,所以它没有检测到大小写。问题在于语言环境设置,更具体地说是LC_COLLATE变量。需要将其设置为“C”以考虑大小写。但更好的解决方案是使用字符类而不是范围表达式。这里的解释帮助我解决了我的问题。最终使用字符类对我有用。
[[ ${#s} -ge 6 && "$s" == *[[:lower:]]* && "$s" == *[[:upper:]]* && "$s" == *[0-9]* ]]

