首页 > 编程语言 > 详细

javascript正则表达式RegExp的静态属性之$1-$9

时间:2015-03-13 18:49:49      阅读:557      评论:0      收藏:0      [点我收藏+]

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





javascript正则表达式RegExp的静态属性之$1-$9

原文:http://blog.csdn.net/aitangyong/article/details/44241963

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!