2013-01-22 66 views
0

匹配的正則表達式我有此代碼,它不工作我怎麼能搶在python

import re 
mystring = "This is my test the string to match the stuff"  
p = re.compile(" the ") 

現在我希望能夠把var1和第二場比賽中的第一場比賽中var2

+1

有你讀了[蟒蛇重新文件尚未](HTTP: //docs.python.org/2/library/re.html)? –

+0

我認爲你是對的,我必須研究整個頁面。我現在正在這樣做。 – user1755071

回答

4

你的意思是這樣嗎?

In [3]: import re 

In [4]: strs= "This is my test the string to match the stuff" 

In [5]: p = re.compile(" the ") 

In [6]: re.findall(p,strs) 
Out[6]: [' the ', ' the '] 

In [7]: var1,var2=re.findall(p,strs) 

In [8]: var1,var2 
Out[8]: (' the ', ' the ') 

如果返回的匹配數大於2,那麼您先切分列表。

var1,var2=[' the ', ' the ',' the '][:2] 

Python的3.x的,你可以採取*的優勢,抓住元素的列表中的其餘部分:

In [2]: var1,var2,*extras=[' the ', ' the ','foo','bar'] 

In [3]: var1 
Out[3]: ' the ' 

In [4]: var2 
Out[4]: ' the ' 

In [5]: extras    #rest of the elements are stored in extras 
Out[5]: ['foo', 'bar'] 
+0

athanks好友,它的作品 – user1755071

+0

@ user55711很高興幫助,在時限結束時隨時接受答案。 –