匹配多行
import re
zen = """Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to explain, it
may be a good idea. Namespaces are one honking great idea -- let's do more of those!
m = re.findall("^If", zen, re.MULTILINE)
print(m)
[if,if]
是应该打印的东西,但我得到的只是[]
答案 0 :(得分:2)
您没有正确复制示例。当您使用^
标志时,re.MULTILINE
与行的开头匹配,因此仅当If
在行的开头时才与之匹配。我没有这本书,但是我想这本书的每一行都有自己的句子。
import re
zen = """Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
m = re.findall("^If", zen, re.MULTILINE)
print(m)
答案 1 :(得分:1)
插入符号^
表示If
必须位于行的开头。删除它,您会得到想要的答案。
import re
zen = """Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to explain, it
may be a good idea. Namespaces are one honking great idea -- let's do more of those! """
m = re.findall("If", zen, re.MULTILINE)
print(m)
答案 2 :(得分:0)
Python的实际Zen每行只有一个句子:
zen = """
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
m = re.findall("^If", zen, re.MULTILINE)
print(m)