IanHacker
IanHacker

Reputation: 581

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(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?

Upvotes: 1

Views: 3653

Answers (2)

2Cubed
2Cubed

Reputation: 3551

To check if the string begins with '50M', use str.startswith('50M'). This will not detect cases where 50M is the suffix (test.50M).

if e_list[num_e].startswith('50M'):
    print(e_list[num_e])

If the suffix is a legitimate place to find the 50M, using in is much cleaner than .find('50M') > 0.

if '50M' in e_list[num_e]:

Upvotes: 2

Kingname
Kingname

Reputation: 1362

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)

Upvotes: 2

Related Questions