Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex: Matching bracket/parenthesis pairs

Tags:

python

regex

I want to catch bracket/parenthesis pairs that are next to each other and get hold of the words inside them. In the following text I want to catch [oh](so) and [bad](things).

[oh](so)funny
[all]the[bad](things)

If I use the regex r'\[(.*?)\]\((.*?)\)' it will catch [oh](so) and [all]the[bad](things), which is not what I want.

What's a good regex to solve this?

like image 561
thameera Avatar asked Apr 24 '26 08:04

thameera


1 Answers

Don't use .*?.

Instead use [^\]]+ and [^\)]+

In other words:

r'\[([^\]]+)\]\(([^\)]+)\)'

like image 163
Lone Shepherd Avatar answered Apr 26 '26 23:04

Lone Shepherd



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!