如何保留URL的第一(域)部分并在此之后屏蔽其他所有内容?
这不起作用:
s= ' Get exciting offers when you book a XX year car June XX - XXXX Click here to book http://abc.in/XXzOK '
import re
formatting = [
[r"http://abc.in/", "http://abc.in/XXXX"]
]
for regex,substitution in formatting:
s = re.sub(regex, substitution, s)
print (s)
域名可以是google.com或yahoo.com之类的名称
预期结果:
Get exciting offers when you book a XX year car June XX - XXXX Click here to book http://abc.in/XXXXX
使用
import re
s = ' Get exciting offers when you book a XX year car June XX - XXXX Click here to book http://abc.in/XXzOK '
s = re.sub(r'(https?://[^/]+/)\S*', r'\1XXXX', s)
print(s)
查看Python证明
正则表达式:
(https?://[^/]+/)\S*
请参阅正则表达式证明。
解释
节点 | 解释 |
---|---|
( |
分组并捕获到\ 1: |
http |
'http' |
s? |
's'(可选(匹配最大数量)) |
:// |
'://' |
[^/]+ |
除以下字符外的任何字符:“ /”(1次或多次(匹配尽可能多的次数)) |
/ |
'/' |
) |
\ 1的结尾 |
\S* |
非空白(\ n,\ r,\ t,\ f和“”以外的所有字符)(0次或多次(匹配尽可能多的次数)) |
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句