juniper-
juniper-

Reputation: 6562

Match parenthesis surrounded by spaces in python with regex

Why doesn't the following code block match the parantheses?

In [27]: import re

In [28]: re.match('.*?([\(]*)', '  (((( ' ).groups()
Out[28]: ('',)

Upvotes: 0

Views: 59

Answers (2)

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

In your case .*? means everything because you used [\(]* which means 0 or more. So changing * into + will work for you as + means 1 or more.

re.match('.*?([\(]+)', '  (((( ' ).groups()

Upvotes: 1

Floris
Floris

Reputation: 46365

Demonstrating my comment:

import re
>>> re.match('.*?([\(]*)', '   (((( ' ).groups()
('',)
>>> re.match('.*?([\(]+)', '   (((( ' ).groups()
('((((',)
>>> 

Note - you don't even need the backslash inside the [] - since special characters lose their meaning. So

>>> re.match('.*?([(]+)', '   (((( ' ).groups()
('((((',)
>>> 

works too...

This is because your "non greedy" first quantifier (*?) doesn't need to give anything to the second quantifier - since the second quantifier is happy with zero matches.

Upvotes: 2

Related Questions