Javascript RegEx:匹配重复字符两次(如果匹配3次则忽略)

时间:2017-07-04 11:19:07

标签: javascript regex

我正在为包含2种分隔符的令牌解析字符串(类似于胡子模板)。

我需要一个与{{bob}}中的this is {{bob}} a double token匹配的纯注册解决方案。但在this is {{{bob}}} a triple token

中不匹配

我将双重匹配

\{\{[^\{]([\s\S]+?)[^\}]\}\}

但是,它与三{{bob}}内的{{{bob}}}匹配。

如果没有消极的看法,我很难找到一个纯粹的正则表达式解决方案。有什么指针吗?

3 个答案:

答案 0 :(得分:0)

您可以搜索括号外的任何空白字符,如下所示:

$(document).on('auxclick', 'a', function(e) { if (e.which === 2) { //middle Click e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); return false; } return true;

答案 1 :(得分:0)

<强>正则表达式: ^(\}?)\{\{[^\{]([\s\S]+?)[^\}]\}\}

自动生成说明:

^ asserts position at start of the string 1st Capturing Group (\}?) \}? matches the character } literally (case sensitive) ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy) \{ matches the character { literally (case sensitive) \{ matches the character { literally (case sensitive) Match a single character not present in the list below [^\{] \{ matches the character { literally (case sensitive) 2nd Capturing Group ([\s\S]+?) Match a single character present in the list below [\s\S]+? +? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy) \s matches any whitespace character (equal to [\r\n\t\f\v ]) \S matches any non-whitespace character (equal to [^\r\n\t\f ]) Match a single character not present in the list below [^\}] \} matches the character } literally (case sensitive) \} matches the character } literally (case sensitive) \} matches the character } literally (case sensitive) Global pattern flags g modifier: global. All matches (don't return after first match)

答案 2 :(得分:0)

您可以使用以下内容来提取匹配项:

&#13;
&#13;
var s = "this is {{{ bad bob triple}}} a triple token {{bob double}} {{bob}} a double token {{{bad token}}  {{bad token}}}";
var rx = /(?:^|[^{]){{([^{}]*)}}(?!})/g;
var m, res=[];
while(m=rx.exec(s)) {
  res.push(m[1]);
}
console.log(res);
&#13;
&#13;
&#13;

请参阅regex demo here

  • (?:^|[^{]) - 字符串的开头或{
  • 的任何字符
  • {{ - 加倍{
  • ([^{}]*) - 第1组:任何字符{}零次或多次
  • }} - 加倍}
  • (?!}) - 没有立即跟上}