2016-05-20 49 views
0

我有字符串數組:如何查找缺少字母的匹配字符串?

var dict =["johndoe","johnrte","jahnaoi"]; 

我想打一個函數(正則表達式或其他),以檢查是否「STR」與缺失的字母適合的項目之一。缺少字母用「#」表示。 假設缺少字母的字符串是「j#hn#oe」。 我是以這種方式開始的,但我認爲我不會以正確的方式。

 function Checkword(str) { 
     // Check were is the # 
     var indices = [0] 
     for (var i = 0; i < str.length; i++) { 
      if (str[i] === "#") indices.push(i); 
     } 
     var regexel = "/^"; 

     for (var index = 0; index < indices.length; index++) { 
      regexel.concat(str.substring(indices[index - 1], indices[index])); 
      regexel.concat("[a-z]"); 

     } 
     regexel.concat("$/"); 
     var reg = new Regex(regexel); 

     for (r = 0; r < dict.length; i++) { 
      if (reg.test(dict[r]) { 
        console.log(dict[r]); 
      } 

     } 


    } 
    Checkword("j#hn#oe"); 

在這種情況下,它會返回第一個和最後一個項目。評論後

***編輯:

哪個字要經過我的測試:

If str is j#hndo#=> dict[0], dict[2]. 
If str is j####### => dict[0], dict[1], dict[2]; 
IF str is Jonh#oe=> dict[0] 
if str is a#ze#ts=> nothing. 
+3

聽起來像一個面試問題 – Soren

+0

你能澄清的問題是什麼? –

+0

哪些字母在第一個和最後一個項目中缺失? '#' 沒有意義。 – sweaver2112

回答

1

多虧了評論,這是比預期的多很多容易的答案。謝謝!

var dict =["johndoe","johnrte","jahnaoi"]; 

var dict =["johndoe","johnrte","jahnaoi"]; 

function ismissing(str){ 

    while(str.indexOf("#")>0){ 
     str=str.replace('#', '[a-z]{1}'); 
} 

    var reg=new RegExp(str); 
    console.log(reg); 

    for(i=0;i<dict.length;i++){ 

     if(reg.test(dict[i])) 
      {console.log(dict[i])}; 
} 


} 
ismissing("j#hn#o#"); 

輸出=>

/j[a-z]{1}hn[a-z]{1}o[a-z]{1}/ 
johndoe 
jahnaoi 
undefined 
+0

基於我對這個問題的理解,我可能會把它變成'str = str .replace('#','[az] {1}');' – atheaos

+0

幾乎相同,不是嗎? – Sulot

+0

不,用'。*?'可以匹配'johndoe'以及'joooooohndddddoe' ,'joasfdsdfhnasdfdsoe'和'jhnoe'。另外'[az]'是使用的模式OP。 – atheaos

相關問題