什么是合适的正则表达式?

2024-05-20 18:44:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这种任务的正则表达式是什么?--&燃气轮机; 将“[…:”替换为“[”

也就是说,我想用[[]替换[[…]中的*一些文本*。你知道吗

我的代码的问题是它删除了第一个[[]中的*text*

>>> string = "Some text here [[dont remove me]] and some extra text [[remove me:and let this]] here."
>>> clean = re.sub(r'\[\[.+:', '[[', string)
>>> clean
'Some text here [[and let this]] here.'
>>>

Tags: and代码text文本cleanstringheresome
2条回答
re.sub(r'\[\[[^:\]]+:', '[[', string)

使用[^:\]]而不是.来约束要删除的内容在标记中受到限制。你知道吗

使用排除:和结束语]]的表达式,而不是.

r'\[\[(?:[^:\]]|\][^\]])*:'

相关问题 更多 >