gpt4 book ai didi

javascript - 为什么 JavaScript 中 RegExp 的 matchAll 与其他方法如此不同?

转载 作者:行者123 更新时间:2023-11-30 13:58:51 26 4
gpt4 key购买 nike

JavaScript 有一个正则表达式类RegExp。您可以直接创建它们 re = new RegExp(...) 或间接创建它们 re =/.../

大部分传统方法都是我多年编程习惯的

const match = re.match(str);
const isMatch = re.text(str);

但今天我寻找了一个 matchAll 函数并使用它的语法是这样的

const matches = re[Symbol.matchAll](str)

这种查找函数的方式有什么问题?为什么不只是

const matches = re.matchAll(str);

我猜有一些函数使用这种特殊格式是有原因的。其背后的原因是什么?

const re = /a(.)b(.)c/g;
const matches = re[Symbol.matchAll]('a1b2c a3b4c a5b6c');
console.log([...matches]);

最佳答案

I looked for a matchAll function and to use it the syntax is re[Symbol.matchAll](str)

没有。正确的语法是使用 String matchAll method ,像这样:

const matches = str.matchAll(re);

What is the reasoning behind several functions using this special format?

他们遵循协议(protocol)。喜欢 iterable protocolthenable protocol ,它们通常在某些其他方法/语法中内部使用,不应直接调用。这样的协议(protocol)允许自定义实现该功能,提供一个 Hook 来覆盖。

Symbol.matchAll的情况下,它允许将任意对象用作字符串的匹配器。例如:

const integers = {
*[Symbol.matchAll] (str) {
for (const m of str.matchAll(/\d+/g))
yield parseInt(m[0], 10);
}
};

console.log(Array.from("42ab17, 2x".matchAll(integers)))

引入了 matchAllmatch 符号,以允许 extends RegExpclass 在以下情况下覆盖行为与相应的 String 方法进行交互。在实践中,虽然没有强制执行继承关系,但仅存在符号键控方法就足够了。

关于javascript - 为什么 JavaScript 中 RegExp 的 matchAll 与其他方法如此不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724964/

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