我在AngularJS中使用Mustache风格的标签.什么是使用返回的数组中选择最佳的正则表达式只是胡子括号内的文字?
样本数据:
"This could {{be }} a {{ string.with.dots_and_underscores }} of {{ mustache_style}} words which {{could}} be pulled."
Run Code Online (Sandbox Code Playgroud)
预期产量:
['be','string.with.dots_and_underscores','mustache_style','could']
Run Code Online (Sandbox Code Playgroud)
Xop*_*ter 31
如果使用全局搜索.match,JavaScript将不会在其数组输出中提供捕获组.因此,您需要执行两次:一次查找{{...}}对,然后再次从中提取名称:
str.match(/{{\s*[\w\.]+\s*}}/g)
.map(function(x) { return x.match(/[\w\.]+/)[0]; });
Run Code Online (Sandbox Code Playgroud)
Cod*_*ody 12
String.prototype.supplant这将插入{param}handleBars({})之间的任何内容.我知道这个答案有点广泛,但我认为问题可能与插值有关- 无论哪种方式,我建议读者研究正则表达式,无论如何.
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);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
你可以尝试这样做exec():
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]);
Run Code Online (Sandbox Code Playgroud)
像这样的东西
/{{\s?([^}]*)\s?}}/
Run Code Online (Sandbox Code Playgroud)
值将在第一组中(您知道,不是 0 组,是 1 组 :))
还有一点 - 这个正则表达式捕获和之间的所有内容,因此所有标点符号、括号、点等。如果您只需要单词(可能由下划线或空格分隔),这对您更有用:{{}}
/{{\s?[\w\s]*\s?}}/
Run Code Online (Sandbox Code Playgroud)