【问题标题】:How to use REGEX with multiple filters如何将 REGEX 与多个过滤器一起使用
【发布时间】: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
}

【问题讨论】:

    标签: python regex


    【解决方案1】:

    要对多行文本执行正则表达式匹配,您需要使用参数re.MULTILINE 编译您的正则表达式。

    这段代码应该可以按照您的要求运行。

    regex = re.compile("""(DAY\s*\{[^\{\}]*file\ \=\ \"/Users/Shared/docs/doc\.txt\"[^\{\}]*\})""", re.MULTILINE)
    regex.findall(text)
    

    结果:

    ['DAY {\n day 1\n day 2\n file = "/Users/Shared/docs/doc.txt"\n day 3\n end of the month\n}']
    

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 2019-09-26
      • 2012-01-28
      • 2018-12-29
      • 2023-03-13
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多