2016-03-01 73 views
2

因此,让我们说我有一个变量包含一个字符串,我想测试它是否匹配我的正则表达式,并且我想知道哪个规则在返回false时被破坏,有没有办法让我知道?为什么我的字符串不匹配正则表达式的原因Javascript

这里是我的代码,我在测试

var regex = /^(?=.*\d)[a-zA-Z\d]{6,}$/; 
var word = "dudeE1123123"; 

if(word.match(regex)){ 
    console.log("matched"); 
}else{ 
    console.log("did not match"); 
    console.log("i want to know why it did not match"); 
} 

的原因,我想这是我想通知我的用户,对于例如:“你不包括大写字母”或类似的东西

+0

没有办法在javascript中,写自己的正则表达式引擎。 – georg

回答

1

正则表达式应该匹配一些文本字符串。如果它不匹配,它不会保留有关发生故障前匹配的信息。因此,你不能得到关于什么导致你的正则表达式失败的细节。

您可以在else区块中添加一些测试,以查看输入字符串是否没有数字或字母。这样的事情应该已经足够了:

var regex = /^(?=.*\d)[a-zA-Z\d]{6,}$/; 
 
var word = "###"; 
 

 
if(word.match(regex)){ 
 
    console.log("matched"); 
 
}else{ 
 
    console.log("did not match"); 
 
    var msg = ""; 
 
    if (!/[a-zA-Z]/.test(word)) {     // Are there any letters? 
 
    \t msg += "Word has no ASCII letters. "; 
 
    } 
 
    if (!/\d/.test(word)) {      // Are there any digits? 
 
    \t msg += "Word has no digit. "; 
 
    } 
 
    if (word.length < 6) {      // Is the length 6+? 
 
     msg += "Word is less than 6 chars long. "; 
 
    } 
 
    console.log(msg); 
 
}

+0

好主意我会尝试这个,但它有点糟糕的是,JavaScript没有这个功能tu显示你在哪里它不匹配 – nikagar4

+0

我怀疑有这样的正则表达式风味,告诉你。在Perl中,'use re'debug';'是一种检查失败发生的方式,但对于外行来说输出相当混乱。 Python're.DEBUG'没有那么冗长而且没有用于这个目的。 –

0

我看你能做到这一点的唯一方法是通过在“其他”块滤波试图寻找原因。这是一个(不完整和不是100%有效)的例子:

var regex = /^(?=.*\d)[a-zA-Z\d]{6,}$/; 
var specialCharsCheckRegex = /^[a-zA-Z0-9]/; 
var word = "dude1123123"; 
var word2 = "$dude1123123"; 

if(word.match(regex)){ 
    console.log("matched"); 
}else{ 
    console.log("did not match"); 
    if(!word.match(specialCharsCheckRegex)){ 
     console.log("it contained special chars"); 
    }else{ 
    console.log("i want to know why it did not match"); 
    } 
} 
相关问题