javascript - 如何获取两个单词之间的所有内容
问题描述
这个问题是关于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
?
解决方案
你能不能:
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);
推荐阅读
- javascript - 如何防止表单在 Dynamics 365 中保存
- .net - 创建一个不附加嵌套组中任何字符的通用组
- python - 尝试在 Windows PowerShell 中使用 Python 时权限被拒绝,即使具有管理员权限
- msal - MSAL4J 在不指定范围的情况下静默获取令牌
- kubernetes - 增加 Pod 磁盘大小
- r - 绘制半个数据集而不是整个记录
- javascript - JavaScript 正则表达式:我想替换变量的最后 4 个单词
- mysql - 如何将 IntegerField 迁移到 ForeignKey
- java - JasperReports 不会迭代列表列表的元素
- python-3.x - 读写大文本文件python太慢