簡體   English   中英

python regex查找跨越多行的匹配

[英]python regex find match that spans multiple lines

所以我試圖在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信息,如何獲得整個標題字符串? 很多時候, title后的year不正確。 所以我不能使用:

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

一個快速的解決方案是修改您的regex模式

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

取決於您希望正則表達式的通用性。 我猜想您希望您的字符串能夠包含{和},因此使用它來標記模式的結尾將導致問題。 也可能有多個括號。

這是一個主意,如果您在正則表達式的末尾查找單詞year,並且假設它是常數,該怎么辦。

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

使用更新的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

盡管並不是真正需要它,但它提供了替代解決方案。

textwrap可能有用:

import textwrap

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

indent = "   "
print(textwrap.dedent(indent + a))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM