Javascript正则表达式验证密码字符串(转义标点符号)
我正在尝试使用 javascript 验证密码字符串,并且需要一些正则表达式的帮助。我尝试过一些教程,但我认为我在理解如何转义量词和/或元字符方面遇到一些问题。
我想确保密码字符串仅包含以下范围中的一个或多个(最多 32)个字符:
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"012345678901234567890123456789"
"!@#%&/(){}[]=?+*^~-_.:,;"
前三个范围非常简单,但我无法弄清楚最后一个。基本上我的脚本看起来像这样:
var password = "user_input_password";
if (/^[A-Za-z0-9!@#$%...]{1,32}$/.test(password)) {
document.write('OK');
} else {
document.write('Not OK');
}
非常感谢任何帮助或输入,谢谢!
I am trying to validate a password string with javascript and need some help with a regex. I have tried some tutorials, but I think I have some problems understanding how to escape quantifiers and/or metacharacters.
I want to make sure that the password string only contains one or more (max 32) characters from the following spans:
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"012345678901234567890123456789"
"!@#%&/(){}[]=?+*^~-_.:,;"
The first three spans are pretty easy, but I can't figure out the last one. Basically my script looks something like this:
var password = "user_input_password";
if (/^[A-Za-z0-9!@#$%...]{1,32}$/.test(password)) {
document.write('OK');
} else {
document.write('Not OK');
}
Any help or input is highly appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,您可以使用反斜杠
\
转义元字符;然而,在字符类中,唯一需要转义的是]
、\
和-
(^
仅在一开始时有意义)。像[\w!@#%&/(){}[\]=?+*^~\-.:,;]
这样的东西会做你想要的。\w
等于[A-Za-z0-9_]
。所以完整的测试会是这样的:
In general, you can escape a meta-character using a backslash
\
; however, inside a character class, the only ones you have to escape are]
,\
and-
(the^
only has a meaning at the very beginning). Something like[\w!@#%&/(){}[\]=?+*^~\-.:,;]
will do what you want.The
\w
is equal to[A-Za-z0-9_]
.So the full test would be something like:
您还可以匹配所有不被视为空格的字符(空格、换行符、制表符)。
要排除引号(我在示例中没有看到它们),您可以将它们添加到:
You can also match all characters that are not considered white space (space, newline, tab)
To exclude quotes as well (I didn't see them in your example) you can add those in: