Javascript RegExp.test无效

时间:2014-04-11 18:04:33

标签: javascript regex

我正在尝试为强密码编写正则表达式。

/*  Regular expression explained
o Must contain at least one number: (?=.*\d)
o Must contain at least one letter: (?=.*[a-zA-Z])
o Must contain at least one symbol: (?=.*[!@#$*_=|?{}\[\]~\-,.])
o No whitespace:                        (?=\S+$)
o Length 8 - 25 characters long:        .{8,25}
*/

pass = document.getElementById('password').value;
var PwdRegExpStr = "^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$"
var PwdRegExp = new RegExp(PwdRegExpStr);
var PwdRegExpStr2 = "^.*(?=.{8,25})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$?]).*$"
var PwdRegExp2 = new RegExp(PwdRegExpStr2);

var patt =  /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$/
var patt2 = /^.*(?=.{8,25})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/
alert("Pass:"+pass+" = "+PwdRegExp.test(pass)+" = "+PwdRegExp2.test(pass)+" = "+patt.test(pass)+" = "+patt2.test(pass));

当我输入“qwer1234 $”时,我看到以下结果: 通过:qwer1234 $ = false = false = true = true

你能帮助我理解为什么他们并不都是真的评价吗?

由于

1 个答案:

答案 0 :(得分:2)

你的主要问题是逃避错误。当您以字符串文字的形式指定正则表达式时,您必须转义反斜杠。所以这个:

"^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\[\]~\-,.])(?=\S+$).{8,25}$"

......应该是:

"^(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$*_=|?{}\\[\\]~\\-,.])(?=\\S+$).{8,25}$"

在旁注中,我认为(?=\S+$).{8,25}$执行时不需要编写\S{8,25}$。在您的其他版本中,.*之后的额外^毫无意义。它仍然有效,但你正在使正则表达式引擎做的工作比应该做的要多得多。