所以,假设我有一个包含字符串的变量,我想测试它是否与我的正则表达式匹配,我想知道当它返回false时哪个规则被破坏了,有没有办法可以得到它?
这是我正在测试的代码
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 :(得分: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?
msg += "Word has no ASCII letters. ";
}
if (!/\d/.test(word)) { // Are there any digits?
msg += "Word has no digit. ";
}
if (word.length < 6) { // Is the length 6+?
msg += "Word is less than 6 chars long. ";
}
console.log(msg);
}
答案 1 :(得分:0)
我认为你能做到的唯一方法就是过滤掉&#34;否则&#34;阻止试图寻找原因。这是一个(不完整且不是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");
}
}