我試圖通過谷歌的Python的課程提供給一個列表,一些正則表達式的例子和一個新行打印每個輸出的每個輸出。谷歌的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
兩次退出。
請讓我如何獲得的輸出,諸如:
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'>
這完美的作品。非常感謝。
我刪除了'matches.append(the_match'並將print'行更改爲'print(the_match)'並且它工作。我將用新腳本更新我的問題謝謝@ Buzz –