【发布时间】:2017-02-27 04:52:39
【问题描述】:
text 变量描述了三个 DAY:
text = """
DAY {
foo 12 5 A
foo
12345
}
DAY {
day 1
day 2
file = "/Users/Shared/docs/doc.txt"
day 3
end of the month
}
DAY {
01.03.2016 11:15
01.03.2016 11:16
01.03.2016 11:17
}"""
所有三个 DAY 定义都以单词 DAY 开头(在行首),然后是一个空格和一个大括号。结束用总是放在行首的右括号来表示。 所以我们可以说每个 DAY 的边界是在大括号 {} 中定义的。
使用regex 我需要“找到”在其边界内包含file = "/Users/Shared/docs/doc.txt" 行的DAY。
我开始写一个正则表达式:
string = """DAY {\n [A-Za-z0-9]+}"""
result = re.findall(string, text)
但是表达式停止在foo 末尾的空白字符之前找到文本。如何修改表达式,使其返回正文中包含 file = "/Users/Shared/docs/doc.txt" 的第二个 DAY,因此结果如下所示:
DAY {
day 1
day 2
file = "/Users/Shared/docs/doc.txt"
day 3
end of the month
}
【问题讨论】: