替换有时会加倍的字符的单个实例 [英] Replace single instances of a character that is sometimes doubled
问题描述
我有一个字符串,每个字符由管道字符分隔(包括 "|"
本身),例如:
"f|u|n|n|y||b|o|y||a||c|a|t"
我想将所有不在另一个 "|"
旁边的 "|"
替换为空,以获得结果:
"funny|boy|a|cat"
我尝试使用 mytext.replace("|", "")
,但这会删除所有内容并生成一个长字.
这可以通过一个相对简单的正则表达式来实现,而无需链接str.replace
:
说明:\|(?!\|) 将查找后面没有另一个 |
字符的 |
字符.(?!foo) 表示否定前瞻,确保您匹配的任何内容后面都没有 foo.
I have a string with each character being separated by a pipe character (including the "|"
s themselves), for example:
"f|u|n|n|y||b|o|y||a||c|a|t"
I would like to replace all "|"
s which are not next to another "|"
with nothing, to get the result:
"funny|boy|a|cat"
I tried using mytext.replace("|", "")
, but that removes everything and makes one long word.
This can be achieved with a relatively simple regex without having to chain str.replace
:
>>> import re
>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> re.sub('\|(?!\|)' , '', s)
'funny|boy|a|cat'
Explanation: \|(?!\|) will look for a |
character which is not followed by another |
character. (?!foo) means negative lookahead, ensuring that whatever you are matching is not followed by foo.
这篇关于替换有时会加倍的字符的单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!