2012-07-16 85 views
0

假设我有一个网址如下如何从字符串的整数值(可以是URL)在python

url = 'https://www.advertise-example.com/ads/2022/presents' 

现在我想从一开始的整数值2022上面url.we能使用列表切片在这里,但整数值可以增加,所以我用正则表达式,但无法得到确切的结果,谁能告诉我如何做到这一点

在此先感谢........

回答

3
>>> import re 
>>> url = 'https://www.advertise-example.com/ads/2022/presents' 
>>> int(re.search(r'\d+', url).group()) 
2022 
+0

非常感谢你,我正在使用re.match,所以得到错误。 – 2012-07-16 11:10:48

+0

@shivakrishna因为它从头开始检查:) – jamylak 2012-07-16 11:11:42

0
from urlparse import urlsplit 
import re 

url = 'https://www.advertise-example.com/ads/2022/presents' 
spliturl = urlsplit(url) 
int(re.search(r'\d+', spliturl.path).group()) 

可能看re.findall如果你希望或需要在URL中处理更多> 1位...

另外,不使用重:

digits = [int(el) for el in spliturl.path.split('/') if el.isdigit()] 
0

这里是一个解决方案,而无需使用正则表达式

>>> import itertools 
>>> url = 'https://www.advertise-example.com/ads/2022/presents' 
>>> int(next(''.join(g) for k, g in itertools.groupby(url, str.isdigit) if k)) 
2022 
相关问题