大括号、等号和javascript正则表达式

Curly braces, equal sign and javascript regular expression

本文关键字:javascript 正则表达式      更新时间:2023-09-26

我的HTML页面中有以下示例标记:

{#abc,def#}

使用javascript,我需要从这些令牌中提取文本,如下所示:

abc,def

我正在使用此reg exp:

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

但它匹配两组:

组1:{#test,date第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' ]

如果你想支持所有的浏览器/实现,你可能需要增加数组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();
    };
}