首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google的Python课程:迭代正则表达式列表,并在新行上打印每个输出

Google的Python课程:迭代正则表达式列表,并在新行上打印每个输出
EN

Stack Overflow用户
提问于 2016-07-23 01:46:13
回答 2查看 89关注 0票数 0

我正在尝试将Google的Python课程提供的一些正则表达式示例传递到一个列表中,并在新行上打印每个输出。

代码语言:javascript
复制
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时,我得到以下结果:

代码语言:javascript
复制
python regex.py
I found a cat :) word:cat

它只是停滞,不会产生更多的输出。我必须按ctrl+c键2次才能退出。

请告诉我如何获取输出,例如:

代码语言:javascript
复制
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)之后,我的脚本如下:

代码语言:javascript
复制
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)

输出如下:

代码语言:javascript
复制
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'>

这个可以完美地工作。非常感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-23 01:56:43

它永远运行的原因是因为你在for循环中添加了matches。您总是添加到列表中,使列表变得更长,这反过来又使for循环运行,直到它可以到达末尾,但它永远不会到达它。

代码语言:javascript
复制
for the_match in matches:
    print (the_match)
票数 2
EN

Stack Overflow用户

发布于 2016-07-23 01:55:42

你有一个无限循环:

代码语言:javascript
复制
for the_match in matches:
  matches.append(the_match)

这将永远将新项目附加到列表中。我不知道您试图用它来实现什么,但是看起来您可以简单地删除这两行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38532502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档