=8; 2.Contains at-least one digit. 3.Contains exac-6ren">
gpt4 book ai didi

javascript - 字符串的正则表达式模式包含 "at least one digit and allows only two special chars"

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:21 24 4
gpt4 key购买 nike

我对字符串的正则表达式模式有这样的要求:

    1.String length >=8;
2.Contains at-least one digit.
3.Contains exactly two special characters in string.
4.remaining characters are alphabets.

我尝试过这样的:

   "/^(?=.*[0-9]+)(?=.*[@#$%]{2})[0-9@#$%A-Za-z]{8,}$/g"

但在这个例子中我得到:

   1."Example1#@"      --true    (passed my test)
2."Example2#" --false (passed my test)
3."Example3@@##$#" --true (failed my test)

==>在第 3 种情况下,它接受 2 个以上的特殊字符。

如何实现我的要求,请帮我解决一下。

最佳答案

你可以使用

^(?=\D*\d)(?=(?:\w*[@#$%]){2}(?!\w*[@#$%]))[\d@#$%A-Za-z]{8,}

https://regex101.com/r/9iyoIX/2

(?=\D*\d) - 至少一位数字

(?=(?:\w*[@#$%]){2}(?!\w*[@#$%])) - 重复(可选单词字符后跟特殊字符)2 次,然后对更多特殊字符进行负向查找

(?=[\d@#$%A-Za-z]{8,}) - 字符串长度至少为 8 个字符,并且仅包含所需类型的字符

请注意,\d 优于 [0-9] - 更易于阅读。此外,当您在字符串中查找特定类型的一定数量的字符时,否定字符集.* 具有更好的性能。例如,在查找数字时,最好使用

(?=\D*\d)

(?=.*\d)

这会更有效 - 当没有匹配时,正则表达式会更快失败。

关于javascript - 字符串的正则表达式模式包含 "at least one digit and allows only two special chars",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52439047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com