Joba
Joba

Reputation: 817

Regex to match unescaped pairs of braces

I'm currently trying to make a regex to match the closest pair of an opening and closing bracket without matching escaped braces. (And without matching double escape characters infront of a non escaped bracket).

{"asd"} - {"asd"}
\{"test"} - No match
\\{"Apple juice}"} - {"Apple juice}"}
{{"Test"}} - {"Test"}

I'd already be glad to find a regex which just maches unescaped characters without using \KI have tried multiple things but I can't figure out why this regex doesn't work: ((?<!\\)(?=(?:\\{2})*)){

Upvotes: 1

Views: 371

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You can use

(?<!\\)\\[{}]|(\{(?:"[^"\\]*(?:\\.[^"\\]*)*"|[^{}]*)(?:\\.(?:"[^"\\]*(?:\\.[^"\\]*)*"|[^{}]*))*})

See regex demo

The regex matches 2 alternatives:

  • (?<!\\)\\[{}] - an escaped opening or closing brace with no \ in front

OR (this one is captured, so you can grab it by accessing the first capturing group)

  • (\{(?:"[^"\\]*(?:\\.[^"\\]*)*"|[^{}]*)(?:\\.(?:"[^"\\]*(?:\\.[^"\\]*)*‌​"|[^{}]*))*}) - matches and captures into Group 1 a substring starting with
    • \{ - opening brace
    • (?:"[^"\\]*(?:\\.[^"\\]*)*"|[^{}]*) - a quoted string containing any escaped sequences ("[^"\\]*(?:\\.[^"\\]*)*") or 0 or more characters other than { and } ([^{}]*)
    • (?:\\.(?:"[^"\\]*(?:\\.[^"\\]*)*‌​"|[^{}]*))* - matches 0 or more sequences of...
      • \\. - escaped sequence
      • (?:"[^"\\]*(?:\\.[^"\\]*)*‌​"|[^{}]*) - see description above
  • } - closing brace

Upvotes: 3

Related Questions