2013-12-20 242 views
2

int值如果我有一個urlexamle/def/5/,我試圖找到int值從url使用我怎樣才能從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'

我該怎麼做?

+2

什麼錯誤?請分享一個回溯。 – geoffspear

+0

回溯(最近通話最後一個): 文件 「」,1號線,在 文件 「/usr/lib/python2.7/re.py」,線路177,在的findall 回報_compile(圖案,旗) .findall(字符串) 文件「/usr/lib/python2.7/re.py」,第229行,在_compile中 p = _cache.get(cachekey) TypeError:不可用類型:'list' –

+1

請更新您的問題跟蹤反而放在評論中。 – falsetru

回答

8

確保導入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'] 
+0

好吧,我在[0-9]得到了一點,actully我沒有使用「」 ...thanx –

+0

Downvoter:我該如何改進答案? – falsetru

+0

我不是downvoter,但我建議你使用'\ d +'來捕獲所有的數字不只是單個數字的數字。 –

1

這可能是易於使用的「正則表達式」

雖然強大,它是危險的,以及

我不知道您的具體要求,如果你想從任何地方提取數量

uri,是建議的解決方案作品

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

但我假設你想從uri的「固定位置」獲取數字。 如果是的,你可能不希望這樣的結果

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

我相信你可以修改正則表達式來完成這件事,但是我會盡量避免正則表達式,所以我會去這樣的事情

>>> 'examle5/def/5/'.split('/')[-2] 
'5' 

,如果你想使用提取的值,那麼

try: 
    int('examle5/def/5/'.split('/')[-2]) =>> will produce 5 (without quotes) 
except ValueError: 
    <<your code to handle when integer not present in url) 
0

這樣做沒有正則表達式的只是用不同的方式。

from string import digits 
url = 'examle/def/5/' 
nums = [i for i in list(url) if i in list(digits)] 
return "".join(nums)