我有一个文本,看起来是这样的:
去年预算%%表名:预算年份:最近%%基于预算
本年度预算%%表名:预算年度:当前%%已批准:无基于%%表名:费用类型:预测%%
word 表始终在那里。所有冒号分隔的键值对都是可选的。
我解决提取问题的方法是
/%%table( *(\S+):(\S+) *)*%%/mg但是这个表达式只返回每个匹配的最后一个键:值对。示例代码如下:
发布于 2018-08-20 00:16:45
捕获组将执行always capture the last iteration。
你必须遍历这个字符串:
var mystring = 'Last years budget %%table name:budget year:last%% was based on %%tablename:expenses%%.'
const re = /(?:%%table )?([^:\s%]+:[^%\s]+)/g;
while (match = re.exec(mystring)) {
console.log(match[1]);
}
发布于 2018-08-20 01:13:09
您可以尝试另一种方法,使用正则表达式捕获所有表,然后将每个表拆分为键/值对,如下所示:
const mystring = `Last years budget %%table name:budget year:last%% was based on %%tablename:expenses%%.
This years budget %%table name:budget year:current%% approved:no is based on %%table name:expenses type:forecast%%`
const tables = []
mystring.replace(/%%table((?:\s*\S+:\S+)+)\s*%%/g, (table, entries) => tables.push(entries))
tables.forEach((entries, index, array) => {
array[index] = entries.trim().split(/\s+/g).map(entry => entry.split(':'))
})
console.log(tables)
https://stackoverflow.com/questions/51919468
复制相似问题