首页 > 解决方案 > 如何获取两个单词之间的所有内容

问题描述

这个问题是关于regex

我目前正在使用 Node.js 的子进程的execFile. 它返回一个字符串,我试图从多行字符串中获取一个名称数组,如下所示:

   name: Mike
   age: 11

   name: Jake
   age: 20

   name: Jack
   age: 10

我试过了:

const regex_name = /pool: (.*)\b/gm;
let names = string.match(regex_name);
console.log(names); // returns [ 'name: Mike', 'name: Jake', 'name: Jack' ]

但我想要的是:

['Mike', 'Jake', 'Jack']

我应该改变什么regex

标签: javascriptnode.jsregex

解决方案


你能不能:

let names = string.match(regex_name).map(n => n.replace('name: ',''));

您还可以使用matchAll和提取组:

const exp = new RegExp('name:\\s(.+)','g');
const matches = string.matchAll(exp);
const results = [];

for(const match of matches) {
  results.push(match[1]);
}

或功能上:

Array.from(string.matchAll(exp)).map(match => match[1]);

对于旧版本的节点:

const exp = new RegExp('name:\\s(.+)','g');
const results = [];
let match = exp.exec(string);

while(match) {
  results.push(match[1]);
  match = exp.exec(string);
}

const string = `
   name: Mike
   age: 11

   name: Jake
   age: 20

   name: Jack
   age: 10
`;

let names = string.match(/name:\s(.+)/g).map(n => n.replace('name: ',''));

console.log(names);

const exp = new RegExp('name:\\s(.+)','g');
const matches = string.matchAll(exp);
const results = [];

for(const match of matches) {
  results.push(match[1]);
}

console.log(results);

console.log(Array.from(string.matchAll(exp)).map(match => match[1]));

//Node 8 Update
const results2 = [];
let match = exp.exec(string);

while(match) {
  results2.push(match[1]);
  match = exp.exec(string);
}

console.log(results2);


推荐阅读