2016-03-01 39 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"); 
    } 
} 
相關問題