1

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.

0

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.