Reputation: 303
I'm having some trouble when trying to some get some data from within parenthesis. Here's some sample code:
import re
test_string = '123a (456b)'
regex_a = re.match(r'(?P<a>\d+)a', test_string)
regex_b = re.match(r'(?P<b>\d+)b', test_string)
print regex_a
print regex_b
I would have expected the two regex objects to come back with 123 and 456 respectively, but regex_b
returns None
. Here's a python fiddle showing it (not) working: http://pythonfiddle.com/regex-in-parenthesis
I also tried this in Pythex too (here's a link), but in that environment it works!
I'm scratching my head as to what's going on, any help you could give me would be greatly appreciated. I'm using python 2.6 if that makes a difference.
Upvotes: 1
Views: 264
Reputation: 107347
If you want to match the number within parenthesis you can use the following regex :
\((\d+).*\)
Note that you need to escape the parenthesis and use capture grouping for your digit combination (\d+
),also Note that re.match
checks for a match only at the beginning of the string,instead you need to use re.search
:
>>> re.search(r'\((\d+).*\)',test_string).group(1)
'456'
And if you want to find all numbers you can use re.findall
:
>>> re.findall(r'\d+',test_string)
['123', '456']
Upvotes: 1
Reputation: 4282
re.match()
only matches from the beginning of the string. Try re.search()
instead.
Upvotes: 2