在python中查找匹配对象中的字符串
我想在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
不能被应用,因为它是一个匹配对象。那么,我该怎么办?
我认为Python不是你的第一语言,你的代码闻起来像Java。
请不要使用re.compile
,因为这是不必要的。只需使用re.search
或re.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)
解决你的答案。其实,e_list。append(e_found.group(0))给了我想要的(整个文件名)。除此之外,我完全复制了它,它完美地工作。也谢谢你纠正我的迭代。 – IanHacker
要检查字符串是否以'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]:
如需进一步阅读:Python的3 “[正则表达式HOWTO](https://docs.python.org/3/howto/regex.html)” 。 –
您应该为正则表达式使用[raw strings](https://docs.python.org/3/library/re.html#raw-string-notation),以防止与反斜杠和string-vs-regex之间的奇怪交互元字符:'r“。* \。(aaa | bbb)$”'。尽管_this_ regex不需要它,现在开始使用这个习惯会在稍后为你节省麻烦。 –
致@Kevin J. Chase:哎呀,我以为我已经在正则表达式前面放了一个'r',但它却没有。谢谢你提醒我。 – IanHacker