Michael
Michael

Reputation: 115

RegExp: Get text within parentheses

I'm using Python's Regular Expression module, and I'm trying to extract a section of multi-line text wrapped between parenthesis. Here is some example text:

function name1 (
    arg1,
    arg2,
    arg3
);

function name2 (
    arg1,
    arg2,
    arg3
);

The following pattern does work, but its always finding the last closing parenthesis (function name2) and not the first:

re.findall('(?<=\()(.*)(?=\))', text, re.MULTILINE | re.DOTALL)

How can I modify the pattern, so that the first closing parenthesis is matched?

Upvotes: 0

Views: 204

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Change your regex to this, notice the ? after * makes it a non-greedy search:

>>> re.findall('(?<=\()(.*?)(?=\))', text, re.MULTILINE | re.DOTALL)
['\n    arg1,\n    arg2,\n    arg3\n', '\n    arg1,\n    arg2,\n    arg3\n']

Upvotes: 1

Related Questions