【问题标题】:How to find matching string with missing letter?如何找到缺少字母的匹配字符串?
【发布时间】:2016-05-20 18:36:08
【问题描述】:

我有一个带字符串的数组:

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.

【问题讨论】:

  • 听起来像是面试题
  • 你能澄清一下问题是什么吗?
  • 那么第二个项目的第一个和最后一个项目中缺少哪些字母? '#' 没有意义。
  • 可能有多个字母缺失。而且这不是一个面试问题,而是一个个人项目! :)
  • 我怀疑你是否需要比input.test(str.replace('#', '.*?')更复杂的东西。

标签: javascript regex string


【解决方案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

【讨论】:

  • 根据我对这个问题的理解,我可能会这样做str=str.replace('#', '[a-z]{1}');
  • 几乎一样,不是吗?
  • 不,.*? 将匹配 'johndoe' 以及 'joooooohndddddoe'、'joasfdsdfhnasdfdsoe' 和 'jhnoe'。 [a-z] 也是 OP 使用的模式。
  • 你在写!谢谢。我改变它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多