1
我需要查找匹配正則表達式的單詞中的所有字符串。我需要先編譯它然後打印這些文字,這就是我所做的:python常客,編譯和匹配
prog = re.compile(pattern)
result = prog.match(string)
for i in result:
print i
它會引發錯誤。我應該改變什麼?
我需要查找匹配正則表達式的單詞中的所有字符串。我需要先編譯它然後打印這些文字,這就是我所做的:python常客,編譯和匹配
prog = re.compile(pattern)
result = prog.match(string)
for i in result:
print i
它會引發錯誤。我應該改變什麼?
SRE_Match
返回的match
函數是不可迭代的。您可能想遍歷所有匹配項目的列表。在這種情況下,你必須使用findall
功能這樣
result = prog.findall(string)
例如,
import re
prog = re.compile("([a-z])")
result = prog.findall("a b c")
for i in result:
print i
輸出
a
b
c
.match不返回的直接字符串的方法匹配,但是所謂的匹配對象。
就是這樣的。
<_sre.SRE_Match object at 0x0041FC80>
你想要做的是以下幾點:
prog = re.compile(pattern)
matches = prog.findall(string)
for i in matches():
print i
什麼是實際的錯誤? – thefourtheye
請提供一些示例數據,輸入/輸出和您收到的錯誤。 –
「我需要先編譯它」 - 你不需要。重新模塊爲你做。 – georg