正则表达式匹配必需的单词和单词序列

时间:2017-03-01 12:45:22

标签: javascript regex

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

示例字符串

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

感谢您的支持

2 个答案:

答案 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);

您创建一个具有所需所需单词的对象,然后循环遍历它们并检查它们是否经常发生。如果没有单个单词失败,则字符串就可以了。

jsFiddle

答案 1 :(得分:1)

使用String.prototype.match()Array.prototype.reduce()函数的解决方案:

&#13;
&#13;
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));
&#13;
&#13;
&#13;