我之前提出了一个非常详细的问题,但它被标记为重复,即使它不是。
所以我会尝试尽可能地解释我想要做的事情。我想在文本字符串中搜索以特定字母开头的单词,例如" mak"," mind"和"质量" (它们在一个数组中)并且没有任何额外的结果或者" e"或者"呃"。那就是在这种情况下" mak"," make"," maker"," mind"," minde" ," minder"," mass"," masse"," masser"。
我使用的代码只找到数组中每个单词的第一个匹配项,例如" mak"," mind"和"质量"在示例中。
derPro = ['mak','mind', 'mass', ;
for(i = 0; i < derPro.length; i++){
searchTerm = new RegExp(
"\\b" + derPro[i] + "\\b|" +
"\\b" + derPro[i] + "e\\b|" +
"\\b" + derPro[i] + "er\\b,'gi'");
word = testText.match(searchTerm, "gi");
答案 0 :(得分:1)
这应该有效:
var derPro = ['mak','mind', 'mass'];
var searchTerm = new RegExp('\\b((?:' + derPro.join('|') + ')(?:er?)?)\\b', "gi");
//=> /\b((?:mak|mind|mass)(?:er?)?)\b/gi
// now match the regex in a while loop
var matches=[]
while (m = searchTerm.exec('mass maker minde')) matches.push(m[1]);
console.log(matches);
//=> ["mass", "maker", "minde"]
答案 1 :(得分:0)
答案 2 :(得分:0)
这很有效,我知道你要求正则表达式,但我认为这会很有用。
var keys = [
'mak',
'mind',
'mass'
];
var test_words = [
'mak',
'make',
'maker',
'mind',
'mass'
];
var matches = [];
for(var i = 0; i < keys.length; i++) {
var key = keys[i];
for(var ii = 0; ii < test_words.length; ii++) {
var test_word = test_words[ii];
if(test_word.substr(0, key.length) == key) {
if( test_word.substr(-1) == 'e' || test_word.substr(-2) == 'er') {
matches.push(test_word);
}
}
}
}
console.log(matches);
// [make, maker, minde]