![](/img/trans.png)
[英]Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
[英]Make a subgroup reference (\g<1>) optional in re.sub
如何在re.sub()
创建子组引用( \\g<1>
)可选? 例如:
import re
regexp = re.compile(r'^http://(lists\.|www\.)?example\.com/')
regexp.sub(
r'https://\g<1>example.com/',
r'http://example.com/helllo-there'
)
我希望\\g<1>
替换为空,可选子组不匹配(并且不引发异常)。
我知道我可以使用regexp.match(..).groups()
来检查哪些组存在,但这对我来说似乎很多工作(我们需要一堆替换模式,因为一些例子上升到\\g<6>
)。 它也不是很快,因为我们需要进行match
和 replace
。
例如在JavaScript中,我可以使用$1
,如果它不匹配,它只是被忽略:
'http://example.com/helllo-there'.replace(
RegExp('^http://(lists\.|www\.)?example\.com/'),
'https://$1example.com/')
// Outputs: "https://example.com/helllo-there"
另一种选择是提供一个明确的空替代方案:
regexp = re.compile(r'^http://(lists\.|www\.|)example\.com/')
此外,您只能使用\\1
而不是\\g<1>
。
如果我理解正确,只需做x(y?)z
而不是x(y)?z
我会这样做的。 只需将模式放在非捕获组中,并将其设置为可选。 现在在捕获组中包含可选的非捕获组。
>>> re.sub(r'^http://((?:lists\.|www\.)?)example\.com/',r'https://\g<1>example.com/', 'http://example.com/helllo-there')
'https://example.com/helllo-there'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.