Regex Handle Bars

时间:2016-04-25 09:40:32

标签: javascript regex

I have a string like this

"{{hello}}{{{how}}}{{are}}{{{you}}}"

I need to write a regex to only replace the match

2 braces followed by anything except {}, ends with }}

{{hello}} is valid
{{{how}}} is not. Because it has 3 braces

What I tried [^{}]*{{[^{}]+}}[^{}]* but it doesn't seem to work.

Is there a way to get only the matches with 2 braces.


For example, if I want to replace the matches with empty string.

"{{hello}}{{{how}}{{are}}{{{you}}}"

should become

"{{{how}}}{{{you}}}"

2 个答案:

答案 0 :(得分:4)

alert("{{hello}}{{{how}}}{{are}}{{{you}}}".replace(/(^|[^{])\{\{[^{}]*\}\}(?!\})/g, "$1"))

The above regex should match the string which was surrounded by exactly two curly braces.

  • (^|[^{]) should capture start of the line or any character but not of curly brace.
  • \{\{[^{}]*\}\} matches a double curly braced blocks which looks like {{foo}}, {{bar foo bar}}
  • (?!\}) Negative lookahead which asserts that the match won't be followed by a closing curly brace.

Regex Demo

答案 1 :(得分:1)

您可以使用

/(\B|[^{]){{[^{}]*}}(?!})/g

并替换为$1,请参阅此regex demo

这里的要点是,如果字符串中间的{{...}}前面带有非单词字符/字符串开头(\B)或者不是{个字符[^{])。否则,连续的比赛将无法找到。

JS演示:



var re = /(\B|[^{]){{[^{}]*}}(?!})/g; 
var str = '{{hello}}{{{how}}}{{are}}{{{you}}}\n{{{hello}}}{{how}}{{are}}{{{you}}}';
document.body.innerHTML += "----- Input ------<br/>" + str.replace(/\n/g, "<br/>");
var result = str.replace(re, '$1');
document.body.innerHTML += "<br/>----- Result ------<br/>" + result.replace(/\n/g, "<br/>");
&#13;
&#13;
&#13;

<强>更新

这是另一种模仿消极外观的选择:

&#13;
&#13;
var str = '{{hello}}{{{how}}}{{are}}{{{you}}}\n{{{hello}}}{{how}}{{are}}{{{you}}}';
var output = str.replace(/({)?{{[^{}]*}}(?!})/g, function($0, $1){
	return $1 ? $0 : 'x';
});
document.body.innerHTML = output.replace(/\n/g, "<br/>");
&#13;
&#13;
&#13;

如果在{之前有{{它被捕获到第1组并在回调中,我们会检查它是否匹配。如果是,只需将整个比赛放回去,否则,只替换找到的匹配。