Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting text between curly braces in python

Tags:

python

regex

I have a string of text like following

1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 )

And I want to extract abc and memo in the above string. I have the regex as follows [link here] essentially {(?:[^{}])*} But it captures everything (returns abc, cde, memo, bleh)

like image 927
frazman Avatar asked Sep 08 '26 07:09

frazman


1 Answers

I would keep it simple.

import re

s = '1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 )'

s_without_parens = re.sub('\(.+?\)','',s)

text_in_brackets = re.findall('{(.+?)}',s_without_parens)

text_in_brackets

[' abc ', ' memo ']

So you can nest that as re.findall('{(.+?)}',re.sub('\(.+?\)','',s)), but I find it helpful to break it into logical steps.

like image 112
C8H10N4O2 Avatar answered Sep 10 '26 21:09

C8H10N4O2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!