--- title: 'RegExp.prototype[@@match]()' slug: Web/JavaScript/Reference/Global_Objects/RegExp/@@match tags: - JavaScript - RegExp - 正则 translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/@@match ---
对正则表达式匹配字符串时,[@@match]()方法用于获取匹配结果。
{{EmbedInteractiveExample("pages/js/regexp-prototype-@@match.html")}}
regexp[Symbol.match](str)
strmatch 方法会返回一个数组,它包括整个匹配结果,和通过捕获组匹配到的结果,如果没有匹配到则返回null
这个方法在 {{jsxref("String.prototype.match()")}} 的内部调用。例如,下面的两个方法返回相同结果。
'abc'.match(/a/);
/a/[Symbol.match]('abc');
这个方法为自定义 RegExp 子类中的匹配行为而存在。
这个方法的使用方式和 {{jsxref("String.prototype.match()")}} 相同,不同之处是 this 和参数顺序。
var re = /[0-9]+/g; var str = '2016-01-02'; var result = re[Symbol.match](str); console.log(result); // ["2016", "01", "02"]
@@match{{jsxref("RegExp")}} 的子类可以覆写 [@@match]()方法来修改默认行为。
class MyRegExp extends RegExp {
[Symbol.match](str) {
var result = RegExp.prototype[Symbol.match].call(this, str);
if (!result) return null;
return {
group(n) {
return result[n];
}
};
}
}
var re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)');
var str = '2016-01-02';
var result = str.match(re); // String.prototype.match calls re[@@match].
console.log(result.group(1)); // 2016
console.log(result.group(2)); // 01
console.log(result.group(3)); // 02
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('ESDraft', '#sec-regexp.prototype-@@match', 'RegExp.prototype[@@match]')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.RegExp.@@match")}}