Match first instance of Python regex search


I'm looking to the first instance of a match two square brackets using regular expressions. Currently, I am doing

regex = re.compile("(?<=(\[\[)).*(?=\]\])")
r =

which works for lines like


returns string

but when I try it on a separate line:

[[string]] ([[string2]], [[string3]])

The result is

string]] ([[string2]], [[string3

What am I missing?

2/22/2011 5:21:50 AM

Accepted Answer

Python *, +, ? and {n,m} quantifiers are greedy by default

Patterns quantified with the above quantifiers will match as much as they can by default. In your case, this means the first set of brackets and the last. In Python, you can make any quantifier non-greedy (or "lazy") by adding a ? after it. In your case, this would translate to .*? in the middle part of your expression.

10/19/2017 9:23:55 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow