我想在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的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