【问题标题】:Match special characters regex in Javascript (Random place)匹配 Javascript 中的特殊字符正则表达式(随机位置)
【发布时间】:2016-07-14 18:05:00
【问题描述】:

我正在尝试制作一个正则表达式来匹配至少两个特殊字符, 用于密码强度检查器。我现在在 Javascript 中有这个:

if (password.match(/([^A-Za-z0-9]{2,})/)) {
    //Add strength
}

但这会检查至少两个需要在彼此之后的特殊字符。我怎样才能做到,这样它也会检查它是否不是一个接一个的?

例子:

_aaa!* //Match
a!a_a* //Also match

【问题讨论】:

  • /[^A-Za-z0-9].*?[^A-Za-z0-9]/ 似乎可行。那是[special char][zero or more anything, nongreedy][special char]

标签: javascript regex


【解决方案1】:

一种方法:

var password = 'a!a_a*';
var matches = password.match(/([^A-Za-z0-9])/g);

if (matches && matches.length >= 2) {
  console.log('Good');
} else {
  console.log('Bad');
}

console.log(matches);

【讨论】:

  • 我将使用长度,if(password.match(/([^A-Za-z0-9])/).length >= 2)。谢谢^^
  • 确保不要忘记 g 全局修饰符。
【解决方案2】:

您可以为此使用replace

var password = 'a!a_a*';
var specialChars = password.replace(/[A-Za-z0-9]/g, '');

console.log(password, specialChars.length > 1 ? 'OK' : 'Too few special chars');

【讨论】:

    【解决方案3】:

    ^(.*?[\*\& list all the special characters you want to allow here prefixed by \]){2,}.*$

    你可以在这里测试它:https://regex101.com/

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多