2016-07-14 22 views
2

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

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

但是这会检查至少两个特殊字符需要彼此接连。我怎么能做到这一点,以便它也会检查它是不是在彼此之后?

例子:

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

'/ [^ A-ZA-Z0-9] * [^ A-ZA-Z0-9] /'似乎喜欢它的工作。这是'[特殊字符] [零或更多的东西,nongreedy] [特殊字符]' – CollinD

回答

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);

+0

我将使用长度,与if(password.match(/([^ A-Za-z0-9])/)。length > = 2)。谢谢^^ –

+1

确保不要忘记'g'全局修饰符。 – Timo

0

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

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

1

您可以使用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');

相关问题