我的 HTML 页面中有以下示例标记:
{#abc,def#}
使用 javascript 我需要从这些标记中提取文本,如下所示:
abc,def
我正在使用这个 reg exp:
/(({#).*(?=#})) /g
但它匹配两组:
group1: {#test, 日期 组2:{#
如何更改它们以匹配正确的组?
我的 HTML 页面中有以下示例标记:
{#abc,def#}
使用 javascript 我需要从这些标记中提取文本,如下所示:
abc,def
我正在使用这个 reg exp:
/(({#).*(?=#})) /g
但它匹配两组:
group1: {#test, 日期 组2:{#
如何更改它们以匹配正确的组?
> '{#abc,def#}'.match(/{#(.*?)#}/)[1]
'abc,def'
更新
> 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' ]
如果你想支持所有浏览器/实现,你可能需要增加数组属性:
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();
};
}