2013-04-30 82 views
1

下面的函数,它由一个模式的出现将字符串分割不工作时,括号内文字跨多行:正则表达式分割多行

import re 
def header(text): 
    authors = [i.strip() for i in re.split(r'\\and|\\thanks\{.*?\}', text, flags=re.M)] 
    names = filter(None,authors) 
    return '{} and {}'.format(', '.join(names[:-1]), names[-1]) 

print header(r"""John Bar \and Tom Foo\thanks{Testing if this works with 
multiple lines} \and Sam Baz""") 

我不知道,如果是正则表达式错误或者如果我错误地使用split函数中的标志。

回答

2

re.M用于锚定多行字符串。你想要的是re.S,这使得.匹配换行符。

2

你应该使用re.DOTALL标志:

re.S 
re.DOTALL 

充分利用 ''特殊字符完全匹配任何字符,包括 换行符;没有这个标志,'。'将匹配除换行符之外的任何内容。