python - 正则表达式拆分为多行

标签 python regex split

当括号内的文本跨越多行时,以下通过模式的出现拆分字符串的函数不起作用:

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 函数中错误地使用了标志。

最佳答案

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

关于python - 正则表达式拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16308215/

相关文章:

javascript - 单词边界匹配 float 后跟可选空格

c - 在 C 中拆分 ASCII 文本文件

python - 是我的人工编译器 : What is wrong with this Python 2. 5 代码吗?

javascript - jQuery - 在发布请求中传递数组

用于正则表达式的 Python 和 Unicode block

Java String split ("|") 方法调用无法正常工作

Java - 如何在加号上拆分字符串?

python - 如何在 Dataframe 的每一列中搜索异常?

python - 用特定字符包围列表中的字符串

ruby - 在 If, Else 语句中测试正则表达式