gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:15:38 24 4
gpt4 key购买 nike

我正在尝试从 javascript 中最简单的 JSON 中提取值。

搜索后我发现 match 是最接近的解决方案。

但是用 RegExp 的分组尝试这个,它没有给出合适的结果。

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

我的结果

'{"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 :

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned.

移除 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);

关于javascript - 为什么 String#match() 结果不包含捕获的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com