【问题标题】:python regex find match that spans multiple linespython 正则表达式查找跨越多行的匹配项
【发布时间】:2016-12-26 21:29:53
【问题描述】:

所以我试图在 python 中使用正则表达式从 BibTex 中获取字符串。这是我的字符串的一部分:

a = '''title = {The Origin ({S},
        {Se}, and {Te})- {TiO$_2$} Photocatalysts},
   year = {2010},
   volume = {114},'''

我要抓取标题的字符串,即:

The Origin ({S},
        {Se}, and {Te})- {TiO$_2$} Photocatalysts

我目前有这个代码:

pattern = re.compile('title\s*=\s*{(.*|\n?)},\s*\n', re.DOTALL|re.I)
pattern.findall(a)

但它只给了我:

['The Origin ({S},\n            {Se}, and {Te})- {TiO$_2$} Photocatalysts},\n       year = {2010']

如何在没有year 信息的情况下获取整个标题字符串? 很多时候,year 不在title 之后。所以我不能使用:

pattern = re.compile('title\s*=\s*{(.*|\n?)},\s*\n.*year', re.DOTALL|re.I)
pattern.findall(a)

【问题讨论】:

标签: python regex


【解决方案1】:

使用较新的regex module

import regex as re

rx = re.compile(r'''
        (?(DEFINE)
            (?<part>\w+\ =\ \{)
            (?<end>\},)
            (?<title>title\ =\ \{)
        )
        (?&title)(?P<t>(?:(?!(?&part))[\s\S])+)(?&end)
    ''', re.VERBOSE)

string = '''
title = {The Origin ({S},
        {Se}, and {Te})- {TiO$_2$} Photocatalysts},
   year = {2010},
   volume = {114},
'''

title = rx.search(string).group('t')
print(title)
# The Origin ({S},
#    {Se}, and {Te})- {TiO$_2$} Photocatalysts

虽然不是真的需要,但它提供了一种替代解决方案。

【讨论】:

    【解决方案2】:

    textwrap 很有用:

    import textwrap
    
    a = '''title = {The Origin ({S},
            {Se}, and {Te})- {TiO$_2$} Photocatalysts},
       year = {2010},
       volume = {114},'''
    
    indent = "   "
    print(textwrap.dedent(indent + a))
    

    【讨论】:

      【解决方案3】:

      取决于您希望正则表达式的通用程度。我猜您希望您的字符串能够包含 { 和 },因此使用它来标记模式的结尾会导致问题。也可以有多个括号。

      这是一个想法,如果你在正则表达式的末尾查找单词 year 会怎样,假设它是不变的。

      pattern = re.compile('title\s*=\s*{(.*?)},\s*\n\s*year', re.DOTALL|re.I)
      

      【讨论】:

      • 很多时候year 不在title 之后。但是你还是给了我一个新的想法:)
      【解决方案4】:

      一个快速的解决方案是修改您的正则表达式模式

      pattern = re.compile('title\s*=\s*{(.*|\n?)},\s*\n', re.DOTALL|re.I)
      

      【讨论】:

      • 我刚刚发现这是错误的。它也会抓取year
      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多