我正在尝试编写一个正则表达式,它将匹配
[[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的结束括号。我想让它来代替它们。你知道吗
使用ungreedy匹配
.*?
<;~~在+
或*
之后的?
使其匹配尽可能少的字符。默认设置为贪婪,并尽可能多地使用字符。你知道吗您可以使用:
.*
是贪婪的,它可以匹配尽可能多的文本,包括]]
和[[
,因此它可以通过“标记”边界继续前进。你知道吗一个快速的解决方案是通过添加一个
?
:一个更好的解决方案(更健壮、更明确,但速度稍慢)是明确指出我们不能跨越标记边界进行匹配:
说明:
相关问题 更多 >
编程相关推荐