我想在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' ,无法应用'30M.aaa' ,因为它是匹配对象。 然后,我该怎么办?
I'd like to find a string in "match objects" in python, but ".find" does not work. Here is my snippet:
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))... Now e_list is like:
[<_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'>]I'm expecting to have the result:
'50M.aaa' '50M.bbb'While e_list[0].group(0) returns '30M.aaa', .find cannot be applied because it's a match object. Then, what should I do?
最满意答案
我认为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)来获得匹配的项目。
那么,你的代码可以是:
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)I think Python is not your first language, your code smell like Java.
Please do not use re.compile, because it is unnecessary. Just use re.search or re.findall.
And in Python, you can just use:
result = re.findall('.*\.(aaa|bbb)$', file)then, result is a list, you can print it or use for... loop to get every item of it.
As you can also use:
result = re.search('.*\.(aaa|bbb)$', file)the result is a group.
Then you should use result.group(1) to get the the matched item.
SO, your code can be:
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)更多推荐
发布评论