简体   繁体   English

字符串包含方括号时,RegEx断开

[英]RegEx breaking when string contains square brackets

I've been using this regular expression to pull out mustached {{Hello}} content: 我一直在使用此正则表达式提取有胡子的{{Hello}}内容:

/{{\s*[\w\.]+\s*}}/g

It's falling down when the mustached string contains square brackets. 当有胡子的弦包含方括号时,它会下降。 I've been fiddling with it for ages to no avail, could anyone suggest an adjustment that will mean it will match {{Hello[0]}} ? 我一直在摆弄它,但无济于事,有人可以建议调整一下,以使其匹配{{Hello [0]}}吗?

I'm your Huckleberry: 我是你的哈克贝利:

\{\{(.*?)\}\}

I always hack around with these using the excellent http://www.regexr.com/ 我总是使用出色的http://www.regexr.com/来解决这些问题

So, to explain why this works for this situation: 因此,解释一下为什么这种情况适用于这种情况:

  1. First, consider \\{\\{ – we escape (by 'escaping' with a backslash the next character doesn't get evaluated by the expression, eg it just looks for that character) the first character we are looking for (the curly brace). 首先,考虑\\{\\{ –我们逃避了(通过用反斜杠“转义”,下一个字符不会被表达式求值,例如,它只是在寻找那个字符),我们正在寻找的第一个字符(花括号) 。
  2. We then repeat that to get the second curly brace. 然后,我们重复该操作以获取第二个花括号。
  3. Next we open a parenthesis ( to make a 'group' to capture multiple tokens – so we can grab everything inside the braces. 接下来,我们打开一个括号(以创建一个“组”来捕获多个标记-这样我们就可以抓住括号内的所有内容。
  4. The . . matches any characters except line breaks. 匹配除换行符以外的所有字符。
  5. The * matches zero or more of the preceding token (in this case any token except line breaks) *匹配零个或多个前面的令牌(在这种情况下,除换行符外的任何令牌)
  6. The ? ? makes the previous quantifier 'lazy' in that it will match as few as possible. 使前一个量词“懒惰”,因为它将尽可能少地匹配。
  7. Then we close the group ) . 然后我们关闭组)
  8. Finally we close out with the two more escaped characters \\}\\} 最后,我们用另外两个转义字符\\}\\}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM