多行正则表达式替换

leo*_*luk 3 python regex

我想转换一个文本,如:

$$
foo
bar
$$
Run Code Online (Sandbox Code Playgroud)

<% tex
foo
bar
%>
Run Code Online (Sandbox Code Playgroud)

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

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

re.sub(r"\$(.*)\$", r"<% tex \1 %>", text)
Run Code Online (Sandbox Code Playgroud)

......它工作正常.

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

re.sub(r"(?i)\$\$(.*)\$\$", r"<% tex \1 %>", text)
Run Code Online (Sandbox Code Playgroud)

...但它返回:

<% tex  %>
foo
bar
<% tex  %>
Run Code Online (Sandbox Code Playgroud)

为什么?我确定这是微不足道的,但我无法想象.

Rya*_*rom 10

我建议使用re.M(多线)标志,并在捕获中吞噬所有不是美元符号的东西.

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

  • 此解决方案有效 - 甚至不需要多行标记,因为[^\$]包含换行符. (3认同)
  • 多行标志甚至位于错误的位置,因为第三个参数是 `count`。如果你应该做`flag=re.M`。 (2认同)