Regex包含至少1个特殊字符,但不包含特殊字符

问题描述 投票:0回答:1

我想检查密码是否至少包含1个特殊字符,但&&; <>

密码可以包含数字或字母,没有限制。

我已经尝试过类似的事情

/^[^a-zA-Z0-9&\\;<>][\"\?/'[]{}|():!@#$%\^\*`~=\+,.-_]*$/

如何分隔它,以便允许字母和数字以及特定的特殊字符,但不允许其他特殊字符?

我在上面尝试过的正则表达式的输出示例:1 !:假(需要为真,我知道我的正则表达式使带有数字或字母的任何东西都为假)! :真a:错误1:假!&:false(&使所有错误都正确)!)以外的其他任何东西,需要为false)

javascript regex
1个回答
1
投票

让我们呼叫&\;<>“无效字符”,并将任何其他非字母数字字符称为“特殊字符”。 “特殊字符”可以与/[^a-zA-Z0-9&\\;<>]/匹配-也就是说,不是a-zA-Z,不是0-9,并且不是任何无效字符。

现在我们的正则表达式可以搜索以任意数量的有效字符作为前缀或后缀的“特殊字符”:

^[^&\\;<>]*[^a-zA-Z0-9&\\;<>][^&\\;<>]*$

^                                          -> match start of sequence (prevent arbitrary leading characters
 [^&\\;<>]*                                -> match 0 or more non-invalid characters
           [^a-zA-Z0-9&\\;<>]              -> match a mandatory special character
                             [^&\\;<>]*    -> match 0 or more non-invalid characters
                                       $   -> match end of sequence (prevent arbitrary trailing characters)

测试出来:

input:valid { background-color: rgba(0, 255, 0, 0.3); }
input:invalid { background-color: rgba(255, 0, 0, 0.3); }
<input type="text" pattern="[^&\\;<>]*[^a-zA-Z0-9&\\;<>][^&\\;<>]*" placeholder="test strings here" required/>
© www.soinside.com 2019 - 2024. All rights reserved.