python - 如何从 url 获取 int 值

标签 python regex python-2.7

如果我有一个 url喜欢examle/def/5/ ,我试图找到 int来自 url 的值通过使用

re.findall([0-9],'examle/def/5/')

但是我得到一个错误。

Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/re.py", line 177, in findall return _compile(pattern, flags).findall(string) File "/usr/lib/python2.7/re.py", line 229, in _compile p = _cache.get(cachekey) TypeError: unhashable type: 'list'

我该怎么做?

最佳答案

确保导入re

>>> import re

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

>>> re.findall('[0-9]','examle/def/5/')
['5']

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

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

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

>>> re.findall(r'\d+','examle/def/567/')
['567']

关于python - 如何从 url 获取 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705035/

相关文章:

python - 如何在 Python 中为 "in"关键字指定自定义比较器?

当 reloader=True 时,Python 计时器函数使用 Bottle.py 运行两次

python - 安装 PyMSSQL-2.0.0b1 时出现错误 : Unable to find vcvarsall. bat...我缺少什么?

python - 为什么下面的正则表达式代码返回逗号 (,)

qt - QGraphicsView 双击事件和 ScrollHandDrag 模式项问题

python - 安装 Anaconda 后无法在 Mac OS 中运行 conda

python - 使用opencv识别浅灰色背景上的深灰色空心细胞

Python:将字典列表转换为 json

ruby-on-rails - 如何找到@[XX :XXXX] in a string and then find the surrounding text? 的所有实例

java - 正则表达式,逐字符读取(java)