简体   繁体   English

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

[英]Extract all occurrences of a single word before target

In Javascript how can I extract all occurrences of a single word before a specific target? 在Javascript中如何在特定目标之前提取单个单词的所有出现?

Input: "Abc FirstWord Target 123 other stuff SecondWord Target blah blah" 输入:“Abc FirstWord Target 123其他东西SecondWord Target blah blah”

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

Thanks 谢谢

The shortest form : 最短的形式

.match(regex) : retrieves the matches when matching a string against a regular expression. .match(regex) :在将字符串与正则表达式匹配时检索匹配项。

 var str = "Abc FirstWord Target 123 other stuff SecondWord Target blah blah"; var retVal = str.match(/([^\\s])+(?=\\sTarget)/g); console.log(retVal); 

Splitting and reducing : 拆分和减少

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

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

Pure regex answer 纯正的正则表达式答案

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]);
}

Solution with ES6/Includes: ES6 /包含的解决方案:

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/ https://jsfiddle.net/dm69txbc/

Check more info here 在这里查看更多信息

You can use the search() with a regular expression 您可以将search()正则表达式一起使用

    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
    }

This matches any term that is not preceded by the target. 这匹配任何未在目标之前的术语。 If the target must follow the match, use '.*(?!' + target + ').*' + term + '.*(?' + target +')*' 如果目标必须遵循匹配,请使用'.*(?!' + target + ').*' + term + '.*(?' + target +')*'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM