Python 非捕获组在替换输出中不可用
我想用新行(Python 非捕获组在替换输出中不可用,python,regex,regex-group,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
\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)
根据,所需输出应为:
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
你可以自己测试
显然,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
替换
re.sub(pattern,lambda x:“\n”如果在您的模式中x.group(1)else x.group(),s)
,您有一个冗余组-([\\\\\\\]])?
,它必须是\\\\\\\\?
,然后上面的行应该可以工作。一个闭包解决方案是令人满意的。还请添加有关已删除的非捕获组的信息,因为我花了一分钟才发现lambda不是这里唯一的更改。