Javascript - regexp - 在字符串中查找数组中的单词,仅限整个单词。

Javascript  -  regexp  - 在字符串中查找数组中的单词,仅限整个单词。

问题描述:



我必须建立一个RegExp obejct,它将从一个数组中搜索单词,

并且只会发现整个单词匹配。



例如

我有一个单词数组('a','b','c'),

我想要RegExp找到'a'或'b'或'c',但不是'aaa'。



我应该如何建立我的RegExp?

提前致谢!



我的尝试:



我试过这段代码:

Hi,
I have to build a RegExp obejct, that will search words from an array,
and will find only whole words match.

e.g.
I have a words array ('a','b','c'),
and I want the RegExp to find 'a' or 'b' or 'c', but not 'aaa'.

How should I build my RegExp?
Thanks in advance!

What I have tried:

I tried this code:

new RegExp('(word1|word2|word3)','g');





效果很好,但它也找到像word11111这样的单词,我只需匹配整个单词。



It works well, but it find also words like "word11111", I have to match only the whole words.

试试:

Try:
new RegExp('\\b(word1|word2|word3)\\b','g');

\ b 字边界 [ ^ ]所以现在你的正则表达式只匹配完整的单词。



要从包含单词的数组创建:

\b is a word boundary[^] so now your regex will only match full words.

To create this from an array with words:

var words = [ "word1", "word2", "word3" ];
var regex = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');


解决方案是使用XRegExp:



The solution was to use XRegExp:

var re = XRegExp('(^|[^_0-9\\pL])(' + matchWords.join('|') + ')(?![_0-9\\pL])','ig');
text = XRegExp.replace(text.replace(/\n


/ g,'\ nn \'),re,'
/g, '\n\n'), re, '