JavaScript参考手册
RegExp
regExp.@@match
对正则表达式匹配字符串时,[@@match]()
方法用于获取匹配结果。
语法
regexp[Symbol.match](str)
参数
str
match 的目标参数是String
返回值
match 方法会返回一个数组,它包括整个匹配结果,和通过捕获组匹配到的结果,如果没有匹配到则返回null
描述
这个方法在String.prototype.match()
的内部调用。例如,下面的两个方法返回相同结果。
'abc'.match(/a/);
/a/[Symbol.match]('abc');
这个方法为自定义RegExp
子类中的匹配行为而存在。
示例
直接调用
这个方法的使用方式和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
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 |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'RegExp.prototype@@match' in that specification. |
Standard |
Initial defintion. |
ECMAScript Latest Draft (ECMA-262)The definition of 'RegExp.prototype@@match' in that specification. |
Draft |
|
浏览器兼容性
Feature |
Chrome |
Firefox (Gecko) |
Internet Explorer |
Opera |
Safari |
---|---|---|---|---|---|
Basic support |
(Yes) |
49 (49) |
No support |
(Yes) |
(Yes) |
Feature |
Android |
Chrome for Android |
Firefox Mobile (Gecko) |
IE Mobile |
Opera Mobile |
Safari Mobile |
---|---|---|---|---|---|---|
Basic support |
(Yes) |
(Yes) |
49.0 (49) |
No support |
(Yes) |
(Yes) |
RegExp相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络