这个问题与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
中我应该更改什么?
答案 0 :(得分:2)
你能不能:
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);
答案 1 :(得分:1)
您可以使用split()获取name:
之后的文本,并使用filter()删除undefined
的值。
var str = `
name: Mike
age: 11
name: Jake
age: 20
name: Jack
age: 10
`;
const regex_name = /(.*)\b/gm;
let names = str.match(regex_name);
names = names.map(str => {
if (str.includes("name")) {
return str.split(':').pop().trim();
}
}).filter(item => item);
console.log(names);