4

for a string like "{foo}{bar}" is there an easy

str = "{foo}{bar}"
first, second = str:gmatch(...)...

should give first="foo" and second="bar"

The problem is that foo itself can have some more parentheses, eg:

str = "{foo {baz}{bar}"

so that first = "foo {baz" The bar part has only alphanumerical characters, no parentheses

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Red-Cloud
  • 438
  • 6
  • 13

1 Answers1

4

You may use

first, second = str:match('{([^}]*)}%s*{([^}]*)}')

See the Lua demo online

The str.match function will find and return the first match and since there are two capturing groups there will be two values returned upon a valid match.

The pattern means:

  • { - a { char
  • ([^}]*) - Group 1: any 0+ chars other than }
  • } - a } char
  • %s* - 0+ whitespaces (not necessary, but a bonus)
  • {([^}]*)} - same as above, just there is a Group 2 defined here.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • In this case I'll get `nil`: `str = "{Während|see{Was\\_auch\\_immmer}}{17}"`. But it should return `Während|see{Was\\_auch\\_immmer}` and `17`. I suppose the parentheses in the left part are the problem. – Red-Cloud Oct 07 '18 at 07:11
  • 1
    @Herbert Probably, I am overthinking it here. If you only expect two values `{..}` and then the last `{}`, use a mere `str:match('{(.*)}%s*{(.*)}')`. See [this demo](https://ideone.com/8HE0P9) – Wiktor Stribiżew Oct 07 '18 at 08:12