-1

Is there regex to catch every character except one? For instance every characters in curly brackets until open curly bracket is found, then don't match that. For instance catch:

{lorem ipsuem}

but not:

{lorem ipsum {lorem}

because there is another { within I've tried different solution like:

\{[^\}].+?(?=)\} or \s\{[^\}].+?\s(?!\{)\}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • Sounds like you need a parser more than a regex. – VLAZ Oct 03 '19 at 10:29
  • can you please clarify your requirements, `{[^{]*}` appears to match what you're asking – AD7six Oct 03 '19 at 10:29
  • @AD7six yes that is almost that, but for whatever reason if I have {lorem}} it doesn't stop on first } and cath them both – katastari-dev Oct 03 '19 at 10:34
  • But in the case of `{lorem ipsum {lorem}`, shouldn't you match `{lorem}`? – Booboo Oct 03 '19 at 10:40
  • @RonaldAaronson yes I do, but for instance {lorem ipsum {lorem}}, I need only {lorem}, not {lorem}} like it works now – katastari-dev Oct 03 '19 at 10:43
  • 1
    so use `{[^{}]*}` ? I'm confused what you are wanting to match mostly because of the repeated use of `lorem` - what's a real example of the input string and expected match that doesn't currently work? – AD7six Oct 03 '19 at 10:47
  • @AD7six yes, {[^{}]*} do the trick! many thanks! – katastari-dev Oct 03 '19 at 10:57
  • The answer is [here](https://stackoverflow.com/a/33936729/3832970) and [here](https://stackoverflow.com/a/44708840/3832970). The `{[^{}]*}` is common across regex libraries – Wiktor Stribiżew Oct 03 '19 at 11:12

2 Answers2

0

Depends on your flavour of regex, but something like this /{[^{}]*\}/ should do the trick.

In your example it matches {lorem ipsuem}& {lorem}.

Do you need to use regex though? looks like a perfect case to use a stack if you're ensuring the braces are balanced.

Jaboy
  • 212
  • 1
  • 6
  • thanks, that is almost that, but for whatever reason, if I have {lorem}} it doesn't stop on first } and catch them both – katastari-dev Oct 03 '19 at 10:41
  • Try again, I made an edit. It says match anything between `{}`except for `{`or `}` zero to many times. – Jaboy Oct 03 '19 at 11:15
0
import re

s = """{a} {lorem ipsum {lorem}} {b
c}"""

l = re.findall(r'\{[^{}]+\}', s)
print(l)

Prints:

['{a}', '{lorem}', '{b\nc}']
Booboo
  • 38,656
  • 3
  • 37
  • 60