非捕获组在替换输出中不可用

Non capturing group is not available in the replacement output

我想用新行 (\n) 替换字符串中的多个竖线 (|)。但是,在某些特定情况下,它不应被替换,例如颜色符号字符串。

考虑以下输入:

Sample|text||new line|||cFFFFFF00|HEX|colorText in color|this will be inner new line|cFFFFFFFF|HEX|colorReset color. The following goes into the next line too:||hello world

使用以下 re.sub 调用:

re.sub(r"(?:\|\|\w{9}\|HEX\|color.*?|([\|])?\|\w{9}\|HEX\|color)|(\|)", '\n', input)

根据this test,所需的输出应该是:

Sample
text

new line

||cFFFFFF00|HEX|colorText in color
this will be inner new line|cFFFFFFFF|HEX|colorReset color. The following goes into the next line too:

hello world

相反,输出是:

Sample
text

new line

Text in color
this will be inner new line
Reset color. The following goes into the next line too:

hello world

大家可以自己测试一下here

显然,re.sub方法也是在这里替换非捕获组, 我不想发生这种情况。

我怎样才能正确地用 re.sub 替换 模式中匹配的组

您可以将此正则表达式与捕获组和 lambda 函数一起使用 re.sub:

>>> s=r'Sample|text||new line|||cFFFFFF00|HEX|colorText in color|this will be inner new line|cFFFFFFFF|HEX|colorReset color. The following goes into the next line too:||hello world'
>>> print re.sub(r'(\|\|\w{9}\|HEX\|color.*?|([\|])?\|\w{9}\|HEX\|color)|\|', lambda m: m.group(1) if m.group(1) else '\n', s)
Sample
text

new line
||cFFFFFF00|HEX|colorText in color
this will be inner new line|cFFFFFFFF|HEX|colorReset color. The following goes into the next line too:

hello world
  • 在正则表达式中,我们对要保留在替换字符串中的文本使用捕获组。

  • lambda 函数中的代码检查是否存在第一个捕获组,如果存在则将其放回原处,否则将 | 替换为 \n