我想用新行 (\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
正确替换模式的仅匹配的组?
最佳答案
您可以在 re.sub
中将此正则表达式与捕获组和 lambda
函数一起使用:
>>> 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
.
关于python - 非捕获组在替换输出中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54371377/