我有一個看起來像這樣的URL:url = https://www.sx.com/found/text.html我想用捕獲組替換第三個和第四個斜杠之間的文本,即我想用一個新的字符串(新聞)替換“找到”,如下所示:replace = re.sub(r'(?:/.*/)(.*)/', r'/news/\1', url)期望結(jié)果:replace = https://www.sx.com/news/text.html但是我得到這個結(jié)果:https:/news/text.html我在這里做錯了什么?
2 回答

莫回?zé)o
TA貢獻1865條經(jīng)驗 獲得超7個贊
您可以使用:
>>> url = ' >>> print ( re.sub(r'(.+/)[^/]+(/[^/]*/?)$', r'\1news\2', url) ) https://www.sx.com/news/text.html
正則表達式詳細信息:
(.+/)
:任何字符的 1+ 個 greed 匹配,后跟 。捕獲組 #1/
[^/]+
:匹配任何非字符的 1+/
(/[^/]*/?):匹配下一個,然后是非字符,直到結(jié)束。捕獲組 #2
/
/
$
:完

米脂
TA貢獻1836條經(jīng)驗 獲得超3個贊
雖然你應(yīng)該用它來做這個東西,但你可以嘗試urllib
(//.*/).*/
替換為
\1news/
請參閱演示。
https://regex101.com/r/cuNe0j/1
或者你可以試試這個。這樣,您就不需要處理解析。url
from urlparse import urlparse, urlunsplit x= urlparse("https://www.sx.com/found/text.html") y= x.path.replace("found", "news")print urlunsplit([x.scheme, x.netloc, y, x.query, x.fragment])
添加回答
舉報
0/150
提交
取消