Noodle of Death Noodle of Death - 1 year ago 68
Swift Question

Regex, ignore matches that might occur inside a string

Say for example I have the test string:

this is text "This is a quote { containing } some characters" blah blah { inside }

I would like to match every pair of curly brackets and the text in between using the expression


but ignore any matches that might occur inside of a string, namely the
{ containing }
portion of the string, or even be able to match only
{ text }
of the following test string

more text "text text { { { } " { text } words

Answer Source

Well this works:


But I'm not sure that it's bullet proof. You can view it online:

  • {[^}]*} get the curly content
  • (?=(?:[^"]*"[^"]*"[^"]*)*$) ensure that it's followed by an even number of ".

Note: This regex doesn't take account of escaped double quotes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download