简体   繁体   中英

RegEx breaking when string contains square brackets

I've been using this regular expression to pull out mustached {{Hello}} content:

/{{\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]}} ?

I'm your Huckleberry:

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

I always hack around with these using the excellent 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 \\}\\}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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