正则表达式查找和替换多重

2024-04-19 08:09:49 发布

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

我正在尝试编写一个正则表达式,它将匹配

[[any text or char her]]

在一系列文本中。你知道吗

例如:

My name is [[Sean]]
There is a [[new and cool]] thing here.

用我的正则表达式就可以了。你知道吗

data = "this is my tes string [[ that does some matching ]] then returns."
p = re.compile("\[\[(.*)\]\]")
data = p.sub('STAR', data)

问题是当我有多个匹配实例时:[[hello]]和[[bye]]

例如:

data = "this is my new string it contains [[hello]] and [[bye]] and nothing else"
p = re.compile("\[\[(.*)\]\]")
data = p.sub('STAR', data)

这将匹配hello的开始括号和bye的结束括号。我想让它来代替它们。你知道吗


Tags: andtextrehellonewdatastringis
3条回答

使用ungreedy匹配.*?<;~~在+*之后的?使其匹配尽可能少的字符。默认设置为贪婪,并尽可能多地使用字符。你知道吗

p = re.compile("\[\[(.*?)\]\]")

您可以使用:

p = re.compile(r"\[\[[^\]]+\]\]")

>>> data = "this is my new string it contains [[hello]] and [[bye]] and nothing else"
>>> p = re.compile(r"\[\[[^\]]+\]\]")
>>> data = p.sub('STAR', data)
>>> data
'this is my new string it contains STAR and STAR and nothing else'

.*是贪婪的,它可以匹配尽可能多的文本,包括]][[,因此它可以通过“标记”边界继续前进。你知道吗

一个快速的解决方案是通过添加一个?

p = re.compile(r"\[\[(.*?)\]\]")

一个更好的解决方案(更健壮、更明确,但速度稍慢)是明确指出我们不能跨越标记边界进行匹配:

p = re.compile(r"\[\[((?:(?!\]\]).)*)\]\]")

说明:

\[\[        # Match [[
(           # Match and capture...
 (?:        # ...the following regex:
  (?!\]\])  # (only if we're not at the start of the sequence ]]
  .         # any character
 )*         # Repeat any number of times
)           # End of capturing group
\]\]        # Match ]]

相关问题 更多 >