繁体   English   中英

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

[英]How to match single words AND combinations of words using 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"]

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

正则表达式方面我很迷失,因此这里的任何帮助将不胜感激。

提前致谢

你好亲近 请稍后添加单个单词。 在这种情况下,在正则表达式的末尾添加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

要捕获单个单词及其组合,可以使用两个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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM