如何从url获取int值

Mai*_*han 2 python regex python-2.7

如果我url喜欢examle/def/5/,我试图通过使用找到int价值url

re.findall([0-9],'examle/def/5/')
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误.

回溯(最近一次调用最后一次):文件"",第1行,在文件"/usr/lib/python2.7/re.py",第177行,在findall中返回_compile(pattern,flags).findall(string)File "/usr/lib/python2.7/re.py",第229行,在_compile中p = _cache.get(cachekey)TypeError:unhashable type:'list'

我怎样才能做到这一点?

fal*_*tru 8

确保导入re.

>>> import re
Run Code Online (Sandbox Code Playgroud)

将第一个参数作为字符串对象传递.(没有引号[0-9]的列表文字相当于[-9].)

>>> re.findall('[0-9]','examle/def/5/')
['5']
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你可以使用\d而不是[0-9]匹配数字(使用r'raw string'你不需要逃脱\):

>>> re.findall(r'\d','examle/def/5/')
['5']
>>> re.findall(r'\d','examle/def/567/')
['5', '6', '7']
Run Code Online (Sandbox Code Playgroud)

如果要返回单个数字而不是多个数字,请使用\d+:

>>> re.findall(r'\d+','examle/def/567/')
['567']
Run Code Online (Sandbox Code Playgroud)