我正在尝试将Google的Python课程提供的一些正则表达式示例传递到一个列表中,并在新行上打印每个输出。
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当我运行python regex.py时,我得到以下结果:
python regex.py
I found a cat :) word:cat它只是停滞,不会产生更多的输出。我必须按ctrl+c键2次才能退出。
请告诉我如何获取输出,例如:
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...我在Windows 10版本10.0.10586 64位上运行Python 3.5.2。
谢谢!
在你回答(@Buzz)之后,我的脚本如下:
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)输出如下:
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'>这个可以完美地工作。非常感谢。
发布于 2016-07-23 01:56:43
它永远运行的原因是因为你在for循环中添加了matches。您总是添加到列表中,使列表变得更长,这反过来又使for循环运行,直到它可以到达末尾,但它永远不会到达它。
for the_match in matches:
print (the_match)发布于 2016-07-23 01:55:42
你有一个无限循环:
for the_match in matches:
matches.append(the_match)这将永远将新项目附加到列表中。我不知道您试图用它来实现什么,但是看起来您可以简单地删除这两行。
https://stackoverflow.com/questions/38532502
复制相似问题