日期:2014-05-16  浏览次数:20405 次

js正则如何按下面这个要求匹配?

?

?

<SCRIPT LANGUAGE="JavaScript">
	<!--
		var str = '[id:0,name:"name"][aa:"bb",id:1,name:"name"][id:2,name:"name1"]';
		//var patrn=/^\[.*id:1.*\]$/; //这个是死的,而且不正确
		document.write(patrn.exec(str));
	//-->
</SCRIPT>
?

?

有这样一段字符串,每个中括号id唯一,要求匹配指定id中括号里的内容.

?

匹配结果:[aa:"bb",id:1,name:"name"]

1 楼 gwjjeff 2011-07-13  
var str = '[id:0,name:"name"][aa:"bb",id:1,name:"name"][id:2,name:"name1"]';
var p = new RegExp("id:1");
str.replace(/\[.+?\]/g, function(m){if (p.test(m)) {console.log("bingo: " + m)}});
2 楼 wenjinglian 2011-07-26  
gwjjeff 写道
var str = '[id:0,name:"name"][aa:"bb",id:1,name:"name"][id:2,name:"name1"]';
var p = new RegExp("id:1");
str.replace(/\[.+?\]/g, function(m){if (p.test(m)) {console.log("bingo: " + m)}});

谢谢