4

I've this regex: {([^}]+)}

It successfully captures bracket contents, e.g. hello {foo} and {bar}.

I also want to capture groups inside that match separated by a character, e.g. hello {foo:bar} and {hello:world}.

The former would produce a match on {foo:bar} with groups {foo} and {bar} and the latter {hello:world} with groups {hello} and {world}.

I'm not fluent in regex, and I've tried this: {([^}]+)(:([^}]))?} and {([^}]+)(\:([^}]))?} in case the : is a special character.

Which modification do I need to make to succeed?

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37
Vincent
  • 1,119
  • 11
  • 25

1 Answers1

5

To match both types of strings, you may use

{([^{}:]+)(?::([^{}]+))?}

See the regex demo

Details

  • { - a { char
  • ([^{}:]+) - Group 1: one or more chars other than {, } and :
  • (?::([^{}]+))? - an optional sequence of:
    • : - a colon
    • ([^{}]+) - Group 2: 1+ chars other than { and }
  • } - a } char.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Excellent! Thanks for adding description also. – Vincent Sep 26 '18 at 11:23
  • @Vincent You are welcome. I usually omit the description of auxiliary things, but you may read more about [non-capturing groups](https://stackoverflow.com/questions/3512471) (`(?:...)`) and [negated character classes](https://www.regular-expressions.info/charclass.html#negated) (`[^...]`) if you wish. – Wiktor Stribiżew Sep 26 '18 at 11:25