我想在 python 的“匹配对象”中找到一个字符串,但是“.find”不起作用。这是我的片段:
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... 循环
来获取它的每一项。
您还可以使用:
result = re.search('.*\.(aaa|bbb)$', file)
结果是一组。
然后您应该使用result.group(1) 来获取匹配项。
所以,您的代码可以是:
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)
关于python - 在python中的匹配对象中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908699/