首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >须式双花括号的Regex?

须式双花括号的Regex?
EN

Stack Overflow用户
提问于 2013-03-19 22:46:03
回答 5查看 16.5K关注 0票数 30

我在AngularJS中使用了Mustache风格的标签。最好的正则表达式是什么,用来返回一个只包含大括号内文本的数组?

示例数据:

代码语言:javascript
复制
"This could {{be }} a {{ string.with.dots_and_underscores }} of {{ mustache_style}} words which {{could}} be pulled."

预期输出:

代码语言:javascript
复制
['be','string.with.dots_and_underscores','mustache_style','could']
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-03-19 22:56:46

如果将全局搜索与.match一起使用,JavaScript将不会在其数组输出中提供捕获组。因此,您需要执行两次操作:一次是查找{{...}}对,第二次是从其中提取名称:

代码语言:javascript
复制
str.match(/{{\s*[\w\.]+\s*}}/g)
   .map(function(x) { return x.match(/[\w\.]+/)[0]; });
票数 32
EN

Stack Overflow用户

发布于 2015-08-06 01:53:11

道格拉斯·克罗克福德的String.prototype.supplant模型

这将对handleBars ({})之间的任何{param}进行插值。我知道这个答案有点广泛,但我认为这个问题可能是关于插值的--不管怎样,我都建议读者研究正则表达式。

代码语言:javascript
复制
clear();

function interpolate(str) {
    return function interpolate(o) {
        return str.replace(/{([^{}]*)}/g, function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        });
    }
}

var terped = interpolate('The {speed} {color} fox jumped over the lazy {mammal}')({
    speed: 'quick',
    color: 'brown',
    mammal: 'dog'
});

console.log(terped);

希望这能有所帮助

票数 13
EN

Stack Overflow用户

发布于 2013-03-19 23:00:23

您可以尝试使用exec()来执行此操作:

代码语言:javascript
复制
var list = [],
    x = '"This could {{be }} a {{ string }} of {{ mustache_style}} words which {{could}} be pulled."',
    re = /{{\s*([^}]+)\s*}}/g,
    item;

while (item = re.exec(x))
    list.push(item[1]);
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15502629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档