简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM