lundi 26 juin 2017

How to do if statements with regex find all python

I'm currently trying to do some looping through a few strings with some regexes, however I'm doing something wrong when it comes to my iterations. I want to basically have a fail safe if my find all command turns up nothing with an if state. So basically "If nothing in the string matches the regex, do blah" however I have been unsuccessful. I tried is not None, and is not '[]' and is not '' but nothing seems to work. Examples:

content = bob 100
if  re.findall(r'[0-9]', content) is not None:
print re.findall(r'\b\d+\b', content)

This would print 100

content = bob 200
if  re.findall(r'[0-9]', content) is not None:
print re.findall(r'\b\d+\b', content)

This would print 200

content = bob threehundred
if  re.findall(r'[0-9]', content) is not None:
print re.findall(r'\b\d+\b', content)

This would give the following error:

Traceback (most recent call last): File "test.py", line 14, in number = y[0] IndexError: list index out of range

Please let me know what I am doing wrong

Aucun commentaire:

Enregistrer un commentaire