使用正则表达式从字符串中获取数组

时间:2014-06-30 14:17:53

标签: javascript regex

代码:

<script language="javascript1.2">
   var re = /^\[\[.+$/;
   var str = '[[FirstName]] [[LastName]] watched "[[$Title]]" and sent you the following               
             comment and link:[[iaf_message/5]][[#if iaf_message/6 
              No]]http://webcasts.advanstar.com/acc/iaf/1/[[$PROGRAMID]]/Clicking the 
             URL above will take you to the webcast: "[[$Title]]" 
             [[#else]]http://webcasts.advanstar.com/acc/iaf/1/[[$PROGRAMID]]/?
              _IAFSegment=[[$SEGMENT]]&_IAFTime=[[$posmmss]]Clicking the URL above will 
              take you to the webcast "[[$Title]]" at the point in the program that 
              [[/User/FirstName]] thought would be most relevant to you.
              [[#endif]]Message from Advanstar Communications[Sender IP: [[$IP]]] If 
              you believe you have received this email in error, or for customer 
              service at Accela Communications, please send a message to 
              mailto:support.getinfoadvanstar.com';

  var myArray = str.match(re);
  console.log(myArray);
</script>

我想使用正则表达式获取数组中[[]]内所有值的所有值。请帮帮我。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

var myArray = str.match(/\[\[.+?\]\]/g).map(
    function(x){ return x.replace(/\[|\]/g,"");
});

答案 1 :(得分:1)

这适用于所有版本的JavaScript:

var mystring = "[[foo]] .. [[bar]] ... [[baz]]";
var pattern = /\[\[([^\]]*)\]\]/g
var array = [];
match = pattern.exec(mystring);
while (match !== null) {
  array.push(match[1]);
  match = pattern.exec(mystring);
}