Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Regexp匹配强制单词和单词序列_Javascript_Regex - Fatal编程技术网

Javascript Regexp匹配强制单词和单词序列

Javascript Regexp匹配强制单词和单词序列,javascript,regex,Javascript,Regex,我想匹配一个包含必填单词或单词序列的字符串。我甚至不知道我是否可以用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 d

我想匹配一个包含必填单词或单词序列的字符串。我甚至不知道我是否可以用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

感谢您的支持

您可以这样做:

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);
创建一个对象,其中包含所有必需的单词和所需的数量,然后循环遍历它们并检查它们是否经常出现。如果没有一个单词失败,那么字符串就正常了

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

函数checkMandatoryWordsstr,字集{ var result=Object.keywordset.reducefunction r,k{ var m=str.matchnew RegExp'\\b'+k+'\\b',g'; r[k]=m?m.length:0;//写入出现的次数 如果m&&m.length!==wordSet[k]r.Success=false; 返回r; },{成功:正确}; 返回结果; } var str=不,我不相信他会冷酷无情\ 她不做作,太感情用事\ 他在那个里为你们开门的房间,你们会知道的\ 教育是如此的亲切\ 他剩下的和自己沮丧的女儿都是运动员\ 他很容易就学会了, 单词集={房间:1,卓越:2,教育:1,房子:1};
console.logcheckMandatoryWordsstr,wordSet;嘿,谢谢,这正是我现在正在编写的代码!谢谢你的时间,我能问你其他问题吗?如果我有两个必填字符串,如-my name-name和一个句子,如“my name is john”,那么在这种情况下,我如何确保只匹配“my name”而不匹配“name”?