2016-05-20 47 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

相关问题