IanHacker IanHacker - 1 year ago 44
Python Question

Finding a string in match objects in python

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(".*\.(aaa|bbb)$")
e_found = r.search(file)
if e_found is not None:

e_length = len(e_list);

for num_e in range(e_length):
if(e_list[num_e].group(0).find('50M') > 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:



While "e_list[0].group(0)" returns '30M.aaa', ".find" cannot be applied because it's a match object. Then, what should I do?

Answer Source

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:

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