在字符串中查找数组中的单词,仅限整个单词(使用希伯来字符) [英] Find words from array in string, whole words only (with hebrew characters)
问题描述
我必须构建一个RegExp obejct,它将搜索数组中的单词
,并且只能查找整个单词匹配。
I have to build a RegExp obejct, that will search words from an array, and will find only whole words match.
例如。
我有一个单词数组('יל','ילד'),
我希望RegExp找到'a'或'ל'或'ל'',但不是'לל''。
e.g. I have a words array ('יל','ילד'), and I want the RegExp to find 'a' or 'יל' or 'ילד', but not 'ילדד'.
这是我的代码:
var text = 'ילד ילדדד יל';
var matchWords = ['יל','ילד'];
text = text.replace(/\n$/g, '\n\n').replace(new RegExp('\\b(' + matchWords.join('|') + ')\\b','g'), '<mark>$&</mark>');
console.log(text);
我试过的:
我试过这段代码:
new RegExp('(יל|ילד)','g');
它运作良好,但它也找到像ילדדדד这样的词,我只能匹配整个单词。
It works well, but it find also words like "ילדדדד", I have to match only the whole words.
我也尝试了这段代码:
new RegExp('\\b(יל|ילד)\\b','g');
但这个正则表达式找不到任何单词!
but this regular expression doesn't find any word!
我应该如何建立我的RegExp?
How should I build my RegExp?
推荐答案
字边界 \ b
不支持Unicode。使用 XRegExp
构建Unicode字边界:
The word boundary \b
is not Unicode aware. Use XRegExp
to build a Unicode word boundary:
var text = 'ילד ילדדד יל';
var matchWords = ['יל','ילד'];
re = XRegExp('(^|[^_0-9\\pL])(' + matchWords.join('|') + ')(?![_0-9\\pL])','ig');
text = XRegExp.replace(text.replace(/\n$/g, '\n\n'), re, '$1<mark>$2</mark>');
console.log(text);
<script src="http://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>
这里,(^ | [^ _ 0-9 \\\\ pL])
是ID = 1的捕获组,它匹配字符串start或任何其他字符串比Unicode字母,ASCII数字或 _
(一个主要单词边界)和(?![_ 0-9 \\\\ pL])
如果后跟单词,则匹配失败 _
,ASCII数字或Unicode字母。
Here, (^|[^_0-9\\pL])
is a capturing group with ID=1 that matches either the string start or any char other than a Unicode letter, ASCII digit or _
(a leading word boundary) and (?![_0-9\\pL])
fails the match if the word is followed with _
, ASCII digit or a Unicode letter.
这篇关于在字符串中查找数组中的单词,仅限整个单词(使用希伯来字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!