python规范,编译和匹配

2024-04-20 14:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在一个单词中找到与正则表达式匹配的所有字符串。我需要先编译然后打印出来,我就是这么做的:

prog = re.compile(pattern)
result = prog.match(string)
for i in result:
    print i

这会引起错误。我该换什么?你知道吗


Tags: 字符串inreforstringmatch错误result
2条回答

match函数返回的SRE_Match不可iterable。您可能希望遍历所有匹配项的列表。在这种情况下,必须像这样使用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方法不直接返回match的字符串,而是一个所谓的match对象。你知道吗

差不多吧。你知道吗

<_sre.SRE_Match object at 0x0041FC80>

您要做的是:

prog = re.compile(pattern)
matches = prog.findall(string)
for i in matches():
    print i

相关问题 更多 >