Matthew
Matthew

Reputation: 33

Regular expression to match content within curly braces without nested braces breaking it

I'm currently matching content within a set of curly braces using {([^}]*)}, but it stops working once I add closing other curly braces inside of it.

I basically want the double curly braces to act as any other text and be apart of the matching group it's nested in, not a separate match or sub-match (not recursive).

{
    <div>
    works
    </div>
}

{
    <div>
    {{fails}}
    </div>
}

Here's a live example of what I currently have: http://regex101.com/r/pT5fA1/4

Any suggestions or advice would be appreciated.

Upvotes: 3

Views: 1838

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89565

I think you are looking for that:

{((?:[^{}]|{{[^}]*}})*)}

Pattern details:

{(
(?:               # non capturing group
    [^{}]         # all that is not a curly bracket
  |               # OR
    {{[^}]*}}     # a string inside double curly brackets
)*                # zero or more times
)}

A more efficient way to do it consits to use an atomic group:

{((?>[^{}]+|{{[^}]*}})*)}

Unfortunatly, Javascript doesn't have this feature. But you can emulate it with a trick that use the fact that the content of a lookahead is naturally atomic:

{((?:(?=([^{}]+|{{[^}]*}}))\2)*)}

Upvotes: 5

Related Questions