Javascript正则表达式验证密码字符串(转义标点符号)

发布于 2024-12-17 20:57:51 字数 531 浏览 2 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫﹏色ふ单纯 2024-12-24 20:57:51

一般来说,您可以使用反斜杠 \ 转义元字符;然而,在字符类中,唯一需要转义的是 ]\-^ 仅在一开始时有意义)。像 [\w!@#%&/(){}[\]=?+*^~\-.:,;] 这样的东西会做你想要的。

\w 等于[A-Za-z0-9_]

所以完整的测试会是这样的:

/^[\w!@#%&/(){}[\]=?+*^~\-.:,;]{1,32}$/.test(password)

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:

/^[\w!@#%&/(){}[\]=?+*^~\-.:,;]{1,32}$/.test(password)
青衫负雪 2024-12-24 20:57:51
/^[A-Za-z0-9!@#%&\/(){}\[\]=?+*^~\-_\.:,;]{1,32}$/
/^[A-Za-z0-9!@#%&\/(){}\[\]=?+*^~\-_\.:,;]{1,32}$/
忘年祭陌 2024-12-24 20:57:51

您还可以匹配所有不被视为空格的字符(空格、换行符、制表符)。

/^[^\s]{1,32}$/.test(password);

要排除引号(我在示例中没有看到它们),您可以将它们添加到:

/^[^\s'"]{1,32}$/.test(password);

You can also match all characters that are not considered white space (space, newline, tab)

/^[^\s]{1,32}$/.test(password);

To exclude quotes as well (I didn't see them in your example) you can add those in:

/^[^\s'"]{1,32}$/.test(password);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文