Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从字符串(Javascript正则表达式)中提取冒号分隔的键值(可选出现)?_Javascript_Regex - Fatal编程技术网

如何从字符串(Javascript正则表达式)中提取冒号分隔的键值(可选出现)?

如何从字符串(Javascript正则表达式)中提取冒号分隔的键值(可选出现)?,javascript,regex,Javascript,Regex,我有一段文字如下: 上年度预算%%表名:预算年度:上年度%基于%%表名:费用% 本年度预算%%表名:预算年度:当前%%approved:no基于 %%表名:费用类型:预测% 单词表总是在那里。所有以冒号分隔的键值对都是可选的 我解决提取问题的方法是 /%%table( *(\S+):(\S+) *)*%%/mg 但是这个表达式只返回每个匹配的最后一个key:value对。下面是示例代码: 捕获组将被删除 您必须迭代字符串: var mystring='Last years budget%%t

我有一段文字如下:

上年度预算%%表名:预算年度:上年度%基于%%表名:费用%

本年度预算%%表名:预算年度:当前%%approved:no基于 %%表名:费用类型:预测%

单词表总是在那里。所有以冒号分隔的键值对都是可选的

我解决提取问题的方法是

/%%table( *(\S+):(\S+) *)*%%/mg
但是这个表达式只返回每个匹配的最后一个key:value对。下面是示例代码:

捕获组将被删除

您必须迭代字符串:

var mystring='Last years budget%%table name:budget year:Last%%基于%%tablename:expenses%%
常量re=/(?:%%表)?([^:\s%]+:[^%\s]+)/g;
while(match=re.exec(mystring)){
console.log(匹配[1]);

}
您可以尝试另一种方法,使用正则表达式捕获所有表,然后将每个表拆分为键/值对,如下所示:

const mystring=`Last years budget%%table name:budget year:Last%%基于%%tablename:expenses%%。
本年度预算%%table name:预算年度:当前%%approved:否基于%%table name:费用类型:预测%%`
常量表=[]
mystring.replace(/%%table((?:\s*\s+:\s+)+)\s*%/g,(table,entries)=>tables.push(entries))
tables.forEach((条目、索引、数组)=>{
数组[index]=entries.trim().split(/\s+/g).map(entry=>entry.split(':'))
})

log(tables)
很抱歉,但我相信regex101示例包含完整的代码。