[英]How to replace a string with parts of it between markers (regex)?
我有一个文本,让我们说:
Lorem ipsum dolor sit [[amet]], consectetur adipiscing elit,
sed do eiusmod [[time (sample)|tempor]] incididunt ut [[labore]] et dolore magna aliqua.
我想用tempor
替换[[time (sample)|tempor]]
。 结构始终相同: [[string to remove|string to extract]]
,并且可以在文本中出现多次。
我在正则表达式中尝试了正则表达式,但没有截断一半文本就没有成功: re.sub(r'\[.*?\|', '', text)
如何替换字符串?
您可以使用以下正则表达式仅收集相关字段
r'\[\[[\w\s\(\)]+?\|(.+?)\]\]'
import re
regex = r'\[\[[\w\s\(\)]+?\|(.+?)\]\]'
text = '''
Lorem ipsum dolor sit [[amet]], consectetur adipiscing elit,
sed do eiusmod [[time (sample)|tempor]] incididunt ut [[labore]] et dolore magna aliqua.
Lorem ipsum dolor sit [[amet]], consectetur adipiscing elit, sed do eiusmod [[time (sample)|tempor]] incididunt ut [[labore]] et dolore magna aliqua.
'''
txt = re.sub(regex, '[[\g<1>]]', text)
print(txt)
Lorem ipsum dolor sit [[amet]], consectetur adipiscing elit,
sed do eiusmod [[tempor]] incididunt ut [[labore]] et dolore magna aliqua.
Lorem ipsum dolor sit [[amet]], consectetur adipiscing elit, sed do eiusmod [[tempor]] incididunt ut [[labore]] et dolore magna aliqua.
Regex101 示例在这里
利用
\[\[(?:(?!\[\[)[^|])*\|(.*?)]]
根据要求替换为[[\1]]
或\1
。
见证明。
解释
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
[^|] any character except: '|'
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
\| '|'
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
]] ']]'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.