在目标之前提取单个单词的所有匹配项

时间:2017-08-17 17:48:07

标签: javascript regex

在Javascript中,如何在特定目标之前提取单个单词的所有出现次数?

输入: “Abc FirstWord Target 123其他东西SecondWord Target blah blah”

输出: [“FirstWord”,“SecondWord”]

由于

5 个答案:

答案 0 :(得分:3)

最短格式

  

.match(regex):在将字符串与正则表达式匹配时检索匹配。

var str = "Abc FirstWord Target 123 other stuff SecondWord Target blah blah";

var retVal = str.match(/([^\s])+(?=\sTarget)/g);


console.log(retVal);

分割和缩小

var str = "Abc FirstWord Target 123 other stuff SecondWord Target blah blah";
var retVal = str.split(/\W/).reduce(function(acc, ele, idx, arr) {
    if (ele == 'Target' && idx > 0) {
       acc.push(arr[idx - 1]);
    }
    return acc;
}, []);

console.log(retVal);

答案 1 :(得分:3)



var str = "Abc FirstWord Target 122 other stuff SecondWord Target";
var regex = /[a-z]*\sTarget/gi, result, els = [];
while ( (result = regex.exec(str)) ) {
    els.push(result[0].replace('Target', '').trim());
}
console.log(els);




答案 2 :(得分:2)

纯正的正则表达式回答

let myString = "Abc FirstWord Target 122 other stuff SecondWord Target";
// match any word character before "Target", g(lobal) flag to get all the matches
let regex = new RegExp(/(\w*) Target/g);

let match = null;
let output = [];
// While we have results
while(match = regex.exec(myString)) {
  // Push the first capture group
  output.push(match[1]);
}

答案 3 :(得分:0)

ES6 / Includes解决方案:

var myString = "Abc FirstWord Target 122 other stuff SecondWord";

var stringNew = myString.split(' ');
var output = [];

stringNew.forEach((i, index) => {
    console.log('item', index, i);
  if(i.includes('Word')) {
    output.push(i);
  }
});

console.log(output);

https://jsfiddle.net/dm69txbc/

查看更多信息here

答案 4 :(得分:0)

您可以将search()regular expression

一起使用
    function getIndexesOfTermBeforeTarget(stringToSearch, term, target) {
      let foundIndexs = [];
      let isSearching = true;
      let regExp = new RegExp('.\*(?!' + target + ').\*' + term + '.\*');
      let lastFoundIndex;
      while(lastFoundIndex !== -1) {
        let lastFoundIndex = stringToSearch.slice(lastFoundIndex).search(regExp);
        if(lastFoundIndex !== -1)(
          foundIndexs.push(index);
        }
      }
      return foundIndexes
    }

这匹配任何未在目标之前的术语。如果目标必须遵循匹配,请使用'.*(?!' + target + ').*' + term + '.*(?' + target +')*'