Search code examples
pythonregexregex-greedy

Python non-greedy regexes


How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?

I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?


Solution

  • You seek the all-powerful *?

    From the docs, Greedy versus Non-Greedy

    the non-greedy qualifiers *?, +?, ??, or {m,n}? [...] match as little text as possible.