Let’s say my full string is this:
blah {something i dont want {sth i want MY STRING blahblah i want } blah
I would like to capture only this part:
{sth i want MY STRING blahblah i want }
Basically anything around and including "MY STRING" until I meet a { and a } on both sides.
I figured it out for the part after MY STRING
with this regex MY STRING.*?(?=})} but I don’t know how to get the first part AKA {sth i want . I tried with some things but all of those get until the first {
>Solution :
That should do the trick:
import re
text = 'blah {something i dont want {sth i want MY STRING blahblah i want } blah'
output = re.findall(r'{[^{]*?MY STRING.*?}', text)[0]
print(output) # {sth i want MY STRING blahblah i want }
You can test it here.
Explanation:
{: Matches a parenthesis.[^{]: Matches a single character that isn’t{*?: Matches the previous character between 0 and unlimited times (lazy).MY STRING: MatchesMY STRING..*?: Matches any character between 0 and unlimited times (lazy).}: Matches a parenthesis.