python - 多行正则表达式替换

标签 python regex

我想转换这样的文本:

$$
foo
bar
$$

<% tex
foo
bar
%>

$\alpha$<% tex \alpha %> .

对于单行替换,我这样做了:

re.sub(r"\$(.*)\$", r"<% tex \1 %>", text)

...而且效果很好。

现在,我添加了多行标志来捕获多行:

re.sub(r"(?i)\$\$(.*)\$\$", r"<% tex \1 %>", text)

...但它返回:

<% tex  %>
foo
bar
<% tex  %>

为什么?我敢肯定这是微不足道的事情,但我无法想象是什么。

最佳答案

我建议使用 re.M(多行)标志,并在捕获中吞噬所有非美元符号的内容。

>>> import re
>>> t = """$$
foo
bar
$$"""
>>> re.sub(r"\$\$([^\$]+)\$\$", r"<% tex \1 %>", t, re.M)
'<% tex \nfoo\nbar\n %>'

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

相关文章:

python - 如何使用 OpenCV 在 Python 中查找图像的平均颜色?

python - pyodbc 在 Python 中连接到 Sybase 数据库

python - 删除非英语行 Pandas

regex - 如何为 CTest 指定正则表达式

regex - 删除多个括号之间的字符串

python - 带有 flat=True 的 Values_list 仍显示括号

python - 如何在ansible playbook中使用正则表达式排除单词?

regex - 按特定模式对文本文件中的列重新排序

R:如何让 grep 返回匹配项,而不是整个字符串

python - 在python中将32位二进制转换为十进制