2013-01-22 61 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很高兴帮助,在时限结束时随时接受答案。 –