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

时间:2019-01-25 19:01:43

标签: python regex regex-group

我想用新行(|)替换字符串中的多个竖线(\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

1 个答案:

答案 0 :(得分:1)

您可以将此正则表达式与捕获组和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

相关问题