Python正则表达式跨行匹配

时间:2015-05-21 16:50:34

标签: python regex

我有一个像这样的bibtex文件:

@inproceedings{baz,
    AUTHOR={{Baz}, {S}. and Bar, {G}. and
      Foo, {M}},
    year={2013}
}

我设法捕获了一个条目(上面显示的整个文本),但是我希望Python中的正则表达式匹配AUTHOR={}括号内的所有内容(跨越换行符)。我怎么能用Python做到这一点?

2 个答案:

答案 0 :(得分:2)

re.compile(r"AUTHOR={([\sA-Za-z{},\.]+)},$", re.MULTILINE)

答案 1 :(得分:1)

您可以使用以下正则表达式检查1级嵌套花括号:

(?ims)author\s*=\s*[{"]((?:[^{}]+?|{[^}]+?})+?)[}"]

请参阅demo

Sample code on IDEONE

import re
p = re.compile(r'(?ims)author\s*=\s*[{"]((?:[^{}]+?|{[^}]+?})+?)[}"]')
test_str = "@inproceedings{baz,\n    AUTHOR = {{Baz}, {S}. and Bar, {G}. and\n      Foo, {M}},\n    year={2013}\n}\n@inproceedings{baz,\n    AUTHOR={{%Baz%}, {S!}. and Bar, {^G^}. and\n      Foo, {<M>}},\n    year={2013}\n}\n"
print [x.group(1) for x in re.finditer(p, test_str)]