javascript正则表达式是支持分组捕获的,分组的结果会存储在RegExp的静态属性$1-$9中。也就是说当正则表达式中的分组超过9个的时候,RegExp最多只保留9个。
// 含10个分组的正则 var regexp = /(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)/; var str = 'a-b-c-d-e-f-g-h-i-j-k-l-m-n-o'; //regexp.test(str); regexp.exec(str); for(var i=1;i<=10;i++) { console.log(RegExp["$"+i]); }
1.The $1, ..., $9 properties are static, there are not a property of an individual regular expression object. Instead, you always use them as RegExp.$1, ..., RegExp.$9.
2.The values of these properties are read-only and modified whenever successful matches are made.
var re = /(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)-(\w)/; var str1 = 'a-b-c-d-e-f-g-h-i-j'; var str2 = 'z-y-x-t-s-r-q-p-o-n'; re.test(str1); for(var i=1;i<=10;i++) { console.log(RegExp["$"+i]); } //匹配失败,$1-$9不变 re.test("a-b-c"); for(var i=1;i<=10;i++) { console.log(RegExp["$"+i]); } //匹配成功,$1-$9改变 re.test(str2); for(var i=1;i<=10;i++) { console.log(RegExp["$"+i]); }
可以参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n
时间: 2024-12-16 11:41:26