host_255 host_255 - 4 months ago 11
Python Question

Google's Python Course: iterating through list of regular expressions and printing each output on a new line

I am trying to pass some regular expressions examples that are provided by Google's Python Course to a list and print each output on a new line.

import re
str='an example word:cat!!'
match=re.search(r'word:\w\w\w',str)
if match:
print('I found a cat :)',match.group()) ## 'found word:cat'
else:
print('did not find')


matches=[re.search(r'pi+', 'piiig'),re.search(r'i+', 'piigiiii'),re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx'),re.search(r'\d\s*\d\s*\d', 'xx12 3xx'),re.search(r'\d\s*\d\s*\d', 'xx123xx'),re.search(r'^b\w+', 'foobar'),re.search(r'b\w+', 'foobar')]
for the_match in matches:
matches.append(the_match)
print("\n".join(matches))
#del matches


When I run
python regex.py
, I get the following:

python regex.py
I found a cat :) word:cat


It just stalls and produces no further output. I will have to press
ctrl+c
2 times to exit.

Please let me how to get an output such as:

re.search(r'pi+', 'piiig') returned (<_sre.SRE_Match object; span=(0, 4), match='piii'>, <_sre.SRE_Match object; span=(1, 3), match='ii'>)
re.search(r'i+', 'piigiiii') returned <_sre.SRE_Match object; span=(1, 3), match='ii'>
etc...


I am running Python 3.5.2 on Windows 10 version 10.0.10586 64 bit.

Thank you!

After your answers (@Buzz), my script is as follows:

import re
str='an example word:cat!!'
match=re.search(r'word:\w\w\w',str)
matches=[re.search(r'pi+', 'piiig'),re.search(r'i+', 'piigiiii'),re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx'),re.search(r'\d\s*\d\s*\d', 'xx12 3xx'),re.search(r'\d\s*\d\s*\d', 'xx123xx'),re.search(r'^b\w+', 'foobar'),re.search(r'b\w+', 'foobar')]

if match:
print('I found a cat :)',match.group()) ## 'found word:cat'
else:
print('No match found.')

for the_match in matches:
print(the_match)


The output is as follows:

I found a cat :) word:cat
<_sre.SRE_Match object; span=(0, 4), match='piii'>
<_sre.SRE_Match object; span=(1, 3), match='ii'>
<_sre.SRE_Match object; span=(2, 9), match='1 2 3'>
<_sre.SRE_Match object; span=(2, 7), match='12 3'>
<_sre.SRE_Match object; span=(2, 5), match='123'>
None
<_sre.SRE_Match object; span=(3, 6), match='bar'>


This works perfectly. Thank you so much.

Answer

The reason it keeps running forever is becasue you are appending to matches inside the for loop. You are always adding to it making the list longer which in turn makes the for loop run until it can reach the end, but it will never reach it.

for the_match in matches:
    print (the_match)
Comments