为什么 String#match() 结果不包含捕获的值?



我正试图从javascript中最简单的JSON中提取一个值。

经过搜索,我发现match是最接近的解。

但是用RegExp的分组来尝试,结果并不理想。

对象是{"a":"one"}我正在构建的正则表达式是new RegExp('{"a":"(.*)"}','g')

my results with

'{"a":"one"}'.match(new RegExp('{"a":"(.*)"}','g'))["{"a":"one"}"]

'{"a":"one"}'.match(new RegExp('{"a":"(.*)"}'.replace(/([+?^=!:${}|[]/\])/g, "\$1"),'g')) 

也是["{"a":"one"}"]

我期待的结果应该是["{"a":"one"}", "one"]

这里出了什么问题?

参见String#match() reference:

如果正则表达式包含g标志,该方法返回一个包含所有匹配子字符串而不是匹配对象的Array。捕获的组不返回。

删除g修饰符以获得预期的结果。

console.log(
   '{"a":"one"}'.match(/{"a":"(.*)"}/)
);
Or, if you need to get multiple matches, use `RegExp#exec` in a loop or - with the latest JS environments - `String#matchAll`:
<!-- begin snippet: js hide: false console: true babel: false -->

matchAll变体:

const s = '{"a":"one","a":"two"}', regex = /"a":"([^"]*)"/g;
const results = Array.from([...s.matchAll(regex)], m => m[1]);
console.log(results);

最新更新