我正在阅读自学程序员ch17的书,无法弄清楚为什么它不起作用

时间:2019-08-14 19:47:37

标签: python

匹配多行

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]是应该打印的东西,但我得到的只是[]

3 个答案:

答案 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)