2017-03-01 63 views
-1

我想匹配包含强制性单词或重复单词序列的字符串。我甚至不知道我是否可以用Regexp来做到这一点。正则表达式匹配强制性单词和单词序列

例串

No depending be convinced in unfeeling he. 
Excellence she unaffected and too sentiments her. 
Rooms he doors there ye aware in by shall. 
Education remainder in so cordially. 
His remainder and own dejection daughters sportsmen. 
Is easy took he shed to kind. 

强制性的话

Rooms (1x) 
Excellence (2x) 
Education (1x) 
House (1x) 

应该返回类似

Success: false 

Rooms: 1 
Excellence: 1 
Education: 1 
House: 0 

感谢支持

回答

1

你可以做这样的事情:

var requiredWords = { 
    Rooms: 1, 
    Excellence: 2, 
    Education: 1, 
    House: 1, 
}; 

var success = true; 
for(var word in requiredWords){ 
    var requiredAmount = requiredWords[word]; 

    //create and check against regex 
    var regex = new RegExp(word, 'g'); 
    var count = (yourString.match(regex) || []).length; 

    //if it doesn't occur often enough, the string is not ok 
    if(count < requiredAmount){ 
    success = false; 
    } 
} 

alert(success); 

您创建一个对象,其中包含所需的所有字,然后遍历它们并检查它们是否经常发生。如果没有一个单词失败,则字符串是OK。

jsFiddle

+0

嘿感谢,这正是我一直在现在的编码!谢谢你的时间 – bln

+0

我可以问你smtg其他吗? 如果我有2个强制性的“串”像 - 我的名字 - 命名 和句子,如“我的名字是约翰 我怎么能相信只匹配“我的名字”,而不是“名称”中这个案例? – bln

1

该解决方案使用String.prototype.match()Array.prototype.reduce()功能:

function checkMandatoryWords(str, wordSet) { 
 
    var result = Object.keys(wordSet).reduce(function (r, k) { 
 
     var m = str.match(new RegExp('\\b' + k + '\\b', 'g')); 
 
     r[k] = m? m.length : 0; // writing the number of occurrences 
 
     if (m && m.length !== wordSet[k]) r.Success = false; 
 

 
     return r; 
 
    }, {Success: true}); 
 

 
    return result; 
 
} 
 

 
var str = "No depending be convinced in unfeeling he. \ 
 
Excellence she unaffected and too sentiments her.\ 
 
    Rooms he doors there ye aware in by shall.\ 
 
    Education remainder in so cordially.\ 
 
    His remainder and own dejection daughters sportsmen.\ 
 
    Is easy took he shed to kind. ", 
 

 
    wordSet = {Rooms: 1, Excellence: 2, Education: 1, House: 1}; 
 

 
console.log(checkMandatoryWords(str, wordSet));

相关问题