【问题标题】:how to use RegExp to check the string has a combination of words in it [duplicate]如何使用RegExp检查字符串中是否包含单词组合[重复]
【发布时间】:2019-07-24 14:49:53
【问题描述】:

有一个字符串,我想测试字符串中是否有多个单词,一种简单的方法是使用循环和includes()方法,但我想知道是否可以使用RegExp进行检查。它

例如,字符串是 'we could accumulate it at the price below 4000' ,我需要检查字符串是否包含单词 'accumulate'、'price'、'below' 的组合。

【问题讨论】:

    标签: javascript regex string


    【解决方案1】:

    你可以使用正则表达式,见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}`);
        });
    }

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2014-01-25
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多