--- title: 'RegExp.prototype[@@matchAll]()' slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll tags: - JavaScript - Method - Prototype - Reference - RegExp - Regular Expressions - メソッド - 正規表現 translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll ---
[@@matchAll] メソッドは、文字列に対する正規表現で一致するすべてのものを返します。
regexp[Symbol.matchAll](str)
strイテレーターです。
このメソッドは内部的に {{jsxref("String.prototype.matchAll()")}} を呼び出します。例えば、以下の2つの例は同じ結果を返します。
'abc'.matchAll(/a/);
/a/[Symbol.matchAll]('abc');
このメソッドは matchAll() の動作を {{jsxref('RegExp')}} のサブクラスの中でカスタマイズするために存在します。
このメソッドは {{jsxref("String.prototype.matchAll()")}}, とほぼ同様に使用することができますが、 this の値と引数の順序が違う点が異なります。
let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[Symbol.matchAll](str); console.log(Array.from(result, x => x[0])); // ["2016", "01", "02"]
{{jsxref("RegExp")}} のサブクラスは [@@matchAll]() メソッドを上書きして既定の動作を変更することができます。
例えば、 {{jsxref("Array")}} をイテレーターの代わりに返すことができます。
class MyRegExp extends RegExp {
[Symbol.matchAll](str) {
const result = RegExp.prototype[Symbol.matchAll].call(this, str);
if (!result) {
return null;
} else {
return Array.from(result);
}
}
}
const re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)', 'g');
const str = '2016-01-02|2019-03-07';
const result = str.matchAll(re);
console.log(result[0]); // [ "2016-01-02", "2016", "01", "02" ]
console.log(result[1]); // [ "2019-03-07", "2019", "03", "07" ]
| 仕様書 |
|---|
| {{SpecName('ESDraft', '#sec-regexp-prototype-matchall', 'RegExp.prototype[@@matchAll]')}} |
{{Compat("javascript.builtins.RegExp.@@matchAll")}}