2016-08-12 61 views
1

我想在python的“匹配对象”中找到一个字符串,但“.find”不起作用。这里是我的代码片段:在python中查找匹配对象中的字符串

e_list = [] 
for file in os.listdir('.'): 
    r = re.compile(r".*\.(aaa|bbb)$") 
    e_found = r.search(file) 
    if e_found is not None: 
     e_list.append(e_found.group(0)) 

e_length = len(e_list); 

for num_e in range(e_length): 
    if(e_list[num_e].group(0).find('50M') > 0) 
     print(e_list[num_e].group(0)) 

...现在e_list就像是:

[<_sre.SRE_Match object; span=(0, 7), match='30M.aaa'>, 
<_sre.SRE_Match object; span=(0, 7), match='40M.bbb'>, 
<_sre.SRE_Match object; span=(0, 7), match='50M.aaa'>, 
<_sre.SRE_Match object; span=(0, 7), match='50M.bbb'>, 
<_sre.SRE_Match object; span=(0, 7), match='50M.ccc'>] 

我期待有结果:

'50M.aaa' 
'50M.bbb' 

虽然e_list[0].group(0)回报'30M.aaa'.find不能被应用,因为它是一个匹配对象。那么,我该怎么办?

+0

如需进一步阅读:Python的3 “[正则表达式HOWTO](https://docs.python.org/3/howto/regex.html)” 。 –

+2

您应该为正则表达式使用[raw strings](https://docs.python.org/3/library/re.html#raw-string-notation),以防止与反斜杠和string-vs-regex之间的奇怪交互元字符:'r“。* \。(aaa | bbb)$”'。尽管_this_ regex不需要它,现在开始使用这个习惯会在稍后为你节省麻烦。 –

+0

致@Kevin J. Chase:哎呀,我以为我已经在正则表达式前面放了一个'r',但它却没有。谢谢你提醒我。 – IanHacker

回答

2

我认为Python不是你的第一语言,你的代码闻起来像Java。

请不要使用re.compile,因为这是不必要的。只需使用re.searchre.findall即可。

而在Python中,你可以使用:

result = re.findall('.*\.(aaa|bbb)$', file) 

然后,result是一个列表,你可以打印或使用for... loop得到它的每一个项目。

正如你也可以使用:

result = re.search('.*\.(aaa|bbb)$', file) 

结果是一组。

然后您应该使用result.group(1)来获取匹配的项目。

SO,代码可以是:

e_list = [] 
for file in os.listdir('.'): 
    e_found = re.search(".*\.(aaa|bbb)$", file) 

    if e_found: 
     e_list.append(e_found.group(1)) 


for item in e_list: 
    if item.find('50M') > 0 
     print(item) 
+0

解决你的答案。其实,e_list。append(e_found.group(0))给了我想要的(整个文件名)。除此之外,我完全复制了它,它完美地工作。也谢谢你纠正我的迭代。 – IanHacker

2

要检查字符串是否以'50M'开头,请使用str.startswith('50M')。这不会检测到50M是后缀(test.50M)的情况。

if e_list[num_e].startswith('50M'): 
    print(e_list[num_e]) 

如果后缀是找到50M一个合法的场所,使用in.find('50M') > 0干净多了。

if '50M' in e_list[num_e]: 
+1

它没有工作。看完Kingname的回答后,我注意到最后一部分应该是: if(e_list [num_e] .find('50M')> 0): print(e_list [num_e]) – IanHacker

+1

@IanHacker啊,我明白了。我已经更新了我的答案是正确的 - 我描述的方式比'.find()'更清晰,更具体。 – 2Cubed

+0

是的,现在它工作。谢谢。 – IanHacker

相关问题