代码之家  ›  专栏  ›  技术社区  ›  John Bustos

Javascript——基于字典/对象中的键解析字符串

  •  1
  • John Bustos  · 技术社区  · 3 年前

    在我的React程序中,假设我有以下字典/对象

    const myDict = {
        "a":"Value 1",
        "b":"Value 2",
        "hello":"Value 3",
        "Bye":"Value 4"
    }
    

    (请注意,没有任何键的值存在于任何其他键中,例如,任何键都不能包含 a 字母(因为这是另一个键)

    我会收到一个字符串 只包含此对象的键的排列 ,因此,例如,可能的字符串条目将是:

    • “abhellob”
    • “你好”
    • “拜赫洛比耶巴”

    我希望创建一个函数,根据 myDict .

    比如说,

    • "abhellob" 会变成 ["a", "b", "hello", "b"]

    如何创建这样的函数?我已经试过了,但是因为要处理不同长度的钥匙而迷路了 麦迪克特 我不知道怎么做。

    2 回复  |  直到 3 年前
        1
  •  4
  •   CertainPerformance    3 年前

    一个在不同键之间交替的正则表达式就可以做到这一点。

    const myDict = {
        "a":"Value 1",
        "b":"Value 2",
        "hello":"Value 3",
        "Bye":"Value 4"
    }
    const pattern = new RegExp(
      Object.keys(myDict).join('|'),
      'g'
    );
    console.log("abhellob".match(pattern));
    console.log("ababByeahello".match(pattern));
    console.log("ByehelloByeba".match(pattern));

    (如果某些关键点可能有字符重叠,那么首先应该对关键点进行排序,以便最长的关键点排在第一位。)

    const myDict = {
        "a":"Value 1",
        "b":"Value 2",
        "hello":"Value 3",
        "Bye":"Value 4"
    }
    const pattern = new RegExp(
      Object.keys(myDict)
        .sort((a, b) => a.length - b.length)
        .join('|'),
      'g'
    );
    console.log("abhellob".match(pattern));
    console.log("ababByeahello".match(pattern));
    console.log("ByehelloByeba".match(pattern));
        2
  •  3
  •   Slava Knyazev    3 年前

    您可以在不使用正则表达式的情况下执行此操作:

    function getFragments(entryString){
      const myDict = {
    "a":"Value 1",
    "b":"Value 2",
    "hello":"Value 3",
    "Bye":"Value 4"
      }
      const keys = Object.keys(myDict);
      
      const result = [];
      let remainingString = entryString;
      while (remainingString) {
    const nextWord = keys.find(key => remainingString.startsWith(key));
    if (!nextWord) throw new Error("Couldn't match with word");
    
    result.push(nextWord);
    remainingString = remainingString.slice(nextWord.length);
      }
      
      return result;
    }
    
    console.log(getFragments("abhellob"));
    console.log(getFragments("ababByeahello"));
    console.log(getFragments("ByehelloByeba"));