gpt4 book ai didi

javascript - 如何获得两个词之间的所有内容

转载 作者:行者123 更新时间:2023-11-30 10:59:36 24 4
gpt4 key购买 nike

这个问题是关于正则表达式的。

我目前正在使用 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 中更改什么?

最佳答案

你能不能:

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

对于旧版本的 Node :

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

关于javascript - 如何获得两个词之间的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58442916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com