簡體   English   中英

在re.sub中創建一個子組引用(\\ g <1>)可選

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM