Javascript - regexp - 在字符串中查找数组中的单词,仅限整个单词。 [英] Javascript - regexp - find words from array in string, whole words only.

查看:94
本文介绍了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, '


这篇关于Javascript - regexp - 在字符串中查找数组中的单词,仅限整个单词。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆