2013-07-25 55 views
0

我有以下我的HTML页面中的样品标记:大括号,等号和JavaScript正则表达式

{#abc,def#} 

使用JavaScript我需要从这些标记中提取文本,像这样:

abc,def 

我使用这个REG EXP:

/(({#).*(?=#})) /g 

但两组匹配:

 
group1: {#test, date 
group2: {# 

如何更改它们以匹配正确的组?

回答

5
> '{#abc,def#}'.match(/{#(.*?)#}/)[1] 
'abc,def' 

UPDATE

> var xs = '{#abc,def#} foobar {#ghi,jkl#}'.match(/{#(.*?)(?=#})/g); 
> for (var i = 0; i < xs.length; i++) xs[i] = xs[i].substr(2); 
> xs 
[ 'abc,def', 'ghi,jkl' ] 

或者一个班轮:

var tokens = (str.match(/{#(.*?)(?=#})/g) || []).map(function(match) 
{ 
    return match.substr(2); 
}); 
console.log(tokens);//[ 'abc,def', 'ghi,jkl' ] 

如果要支持所有浏览器/的,则可能要增加数组proptotype:

if (!Array.prototype.map) 
{ 
    Array.prototype.map = function(callback) 
    { 
     if (typeof callback !== 'function') 
     { 
      throw new TypeError(callback + ' is not a function'); 
     } 
     for(var i = 0;i<this.length;i++) 
     { 
      this[i] = callback(this[i]); 
     } 
     return this.slice(); 
    }; 
} 
+0

这确实会失败,如''{#abc,def#} foobar {#ghi,jkl#}' –

+0

@EliasVanOotegem如何? –

+1

@ m.buettner:在js中没有多组匹配。他们需要使用exec/replace来捕获它们。 – georg

相关问题