user2333196
user2333196

Reputation: 5776

How do I capture words wrapped in parentheses with a regex in Python?

I have this string named jumpball

u'\n               (12:00) Jump Ball Hibbert vs Bosh (Chalmers gains possession)\n            '

I want to extract Hibbert, Bosh and Chalmers

I can find the first by:

roadJumper = re.findall(r'Ball(.*?)vs',jumpball)

The other two names I want to find are before and after a opening parentheses "(" and I don't know how to work around it.

I think I should be able to use lookahead and lookbehind to avoid the parentheses but I haven't figured it out yet.

Upvotes: 0

Views: 359

Answers (2)

André Fratelli
André Fratelli

Reputation: 6068

I think that what you are looking for is how to escape parenthesis, am I right?

Try something like this:

r'Ball (\w+) vs (\w+) \((\w+)'

Notice that the third opening parenthesis is escaped.

If you are now learning how to use regexes I recommend you read this first, if not yet

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113950

>>> print re.search("(\w+) vs (\w+) \(\s?(\w+)",my_string).groups()
(u'Hibbert', u'Bosh', u'Chalmers')

Upvotes: 3

Related Questions