2016-07-14 19 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');

相關問題