Reputation: 10685
I'm trying to apply regex to gather data from a file, and I only get empty results. For example, this little test (python3.4.3
)
import re
a = 'abcde'
r = re.search('a',a)
print(r.groups())
exit()
Results with empty tuple (()
). Clearly, I'm doing something wrong here, but what?
Comment:
What I'm actually trying to do is to interpret expressions such as 0.7*sqrt(2)
, by finding the value inside the parenthesis.
Upvotes: 1
Views: 321
Reputation: 7180
r.groups()
returns an empty tuple, because your regular expression did not contain any group.
>>> import re
>>> a = 'abcde'
>>> re.search('a', a)
<_sre.SRE_Match object; span=(0, 1), match='a'>
>>> re.search('a', a).groups()
()
>>> re.search('(a)', a).groups()
('a',)
Have a look at the re
module documentation:
(...) Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group;
Edit: If you want to catch the bit between the brackets in the expression O.7*sqrt(2)
, you could use the following pattern:
>>> re.search('[\d\.]+\*sqrt\((\d)\)', '0.7*sqrt(2)').group(1)
'2'
Upvotes: 2
Reputation:
It happens because there are no groups in your regex. If you replace it with:
>>> r = re.search('(a)',a)
you'll get the groups:
>>> print(r.groups())
('a',)
Using group
should work with the first option:
>>> print(re.search('a',a).group())
a
Upvotes: 4