4 ms·
Your code does not accomplish the required task. The goal is to return nil when there is no match, or the nth match if there is. >>> re.search('a(x)a', 'axa'
by emmett 17y ago
Your code does not accomplish the required task. The goal is to return nil when there is no match, or the nth match if there is.
>>> re.search('a(x)a', 'axa').group(1)
'x'
>>> re.search('a(x)a', 'aya').group(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
The idiomatic python for the job is:
match = re.search("`([^']*)'", caller[0])
if match:
match.group(1)
else:
None
(or some nonsense involving try/except, which would be even worse).
- jacobolus 17y agoAh, you’re right. In many cases, I don’t want to return None when there’s no match, but for short scripts quickly tossed together, the extra few lines can be a bit annoying. try: re.search("`([^']*)'", caller[0]).group(1) except: None