如何使用正则表达式匹配单个单词和单词组合?

时间:2017-04-11 08:27:43

标签: javascript regex

我正在尝试将用户文本输入与一组预定义的关键字和短语进行匹配。

示例:

var keywordRegEx = /\b(nutrition|protein|muscle|muscle growth|muscle repair|muscle food|foods)\b/ig;

var user_input = "What are the best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx);

console.log(matches); 
//["foods", "muscle", "muscle"]

但我想在控制台中看到的是:

//["foods", "muscle", "muscle growth", "muscle repair"]

有没有办法匹配单个整个单词和组合,包括那些使用正则表达式的整个单词?

*请注意,如果我从预定义的关键字和短语列表中删除“肌肉”,我会得到以下内容:

var keywordRegEx = /\b(nutrition|protein|muscle growth|muscle repair|muscle food|foods)\b/ig;

var user_input = "What are the best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx);

console.log(matches);
//["foods", "muscle growth", "muscle repair"]

但我需要能够自己匹配单个单词..

当谈到正则表达式时我很失落所以任何帮助都会非常感激。

提前致谢

2 个答案:

答案 0 :(得分:2)

你太近了。稍后再添加单个单词。在这种情况下,请在正则表达式的末尾添加muscle

注意:我还更改了输入字符串(添加muscle)只是为了表明正则表达式现在可以抓取单个和多个单词。

const keywordRegEx = /(nutrition|protein|muscle growth|muscle repair|muscle food|foods|muscle)/g;

var user_input = "What are the muscle best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx);

console.log(matches);

在此播放:https://regex101.com/r/Ge5Kry/1

答案 1 :(得分:0)

要捕获单个单词及其组合,您可以使用两个RegExps并将它们组合成单个数组。这样的解决方案更易于阅读,并且可能比单个RegExp更快:



var keywordRegEx = /nutrition|protein|foods|muscle/g;
var keywordPairsRegEx = /muscle growth|muscle repair|muscle food/g;

var user_input = "What are the best foods for muscle growth and muscle repair";
var matches = user_input.match(keywordRegEx) //first regex
            .concat(user_input.match(keywordPairsRegEx)) //second regex
            .filter(( item, index, inputArray ) => { //remove duplicates
              return inputArray.indexOf(item) == index;
            });

console.log(matches);