代码之家  ›  专栏  ›  技术社区  ›  user824624

如何使用RegExp检查字符串中是否有单词组合[duplicate]

  •  -1
  • user824624  · 技术社区  · 7 年前

    例如,字符串是“我们可以以低于4000的价格累计”,我需要检查字符串是否包含“累计”、“价格”、“低于”等词的组合。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dimitri Kopriwa    7 年前

    您可以使用正则表达式,请参见 https://regex101.com/ :

    const regex = /accumulate.*price.*below/gm;
    const str = `we could accumulate it at the price below 4000
    
    we could do it at the price below 4000'`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }