你需要的是re.sub。请注意,方括号和管道都是元字符,因此需要对它们进行转义。re.sub(r'\[\[(?:[^\]|]*\|)?([^\]|]*)\]\]', r'\1', line)
替换字符串中的\1是指括号内匹配的内容,这些内容不以?:(即,在任何情况下,都是您想要的文本)开头。
有两个注意事项。这只允许在打开和关闭支架之间有一个管道。如果有多个,则需要指定是要第一个之后的所有内容还是最后一个之后的所有内容。另一个需要注意的是,不允许在左括号和右括号之间使用单个]。如果这是一个问题,仍然会有一个正则表达式解决方案,但它会相当复杂。
对于模式的完整解释:\[\[ # match two literal [
(?: # start optional non-capturing subpattern for pre-| text
[^\]|] # this looks a bit confusing but it is a negated character class
# allowing any character except for ] and |
* # zero or more of those
\| # a literal |
)? # end of subpattern; make it optional
( # start of capturing group 1 - the text you want to keep
[^\]|]* # the same character class as above
) # end of capturing group
\]\] # match two literal ]