查找重复的两个单词之间的序列

查找重复的两个单词之间的序列

我正在尝试获取水果的数量及其名称。
首先,我想将字符串切成子字符串,因为我知道句子应该在哪里开始和结束。
获得子字符串后,可以检查编号和水果的名称。
我将有一个包含水果名称的数组,每个子字符串仅显示一个数字。

var fruits = ["apple","orange","kiwi","banana"];
var string = 'I want to <start> eat 6 slices of apples <end> in the morning and <start> 1 orange in the evening <end> and <start> 4 more slices of apple before bed <end>'
var pattern = /(?<=<start>\s).*(?=<end>)/g;
var substrings = pattern.exec(string);
var fruit;
for(var i = 0; i < substrings.length; i++){
  for(var j = 0; j < fruits.length; j++){
      fruit = substrings.match(/(fruits[j])/);
   }
  var number = substrings.match(/\d/);
}


我期望输出:10个苹果,1个橙子;

最佳答案

我对您的代码进行了一些编辑,它似乎可以正常工作:



var fruits = ["apple","orange","kiwi","banana"]
var string = 'I want to <start> eat 6 slices of apples <end> in the morning and <start> 1 orange in the evening <end> and <start> 4 more slices of apple before bed <end>'
var pattern = /\<start\>\s*.*?\<end\>/g
var substrings = string.match(pattern)
var fruitsDict = {};
for(var i = 0; i < substrings.length; i++){
  for(var j = 0; j < fruits.length; j++){
    if (substrings[i].match(RegExp(fruits[j]))) {
      num = substrings[i].match(/\d+/)[0]
      fruitsDict[fruits[j]] = (fruitsDict[fruits[j]] || 0) + parseInt(num)
    }
  }
}
console.log(fruitsDict)

关于javascript - 查找重复的两个单词之间的序列-javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55517024/

10-09 01:05