Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex (re.search) in a python list

Tags:

python

regex

list

I have the following code

import re

pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']

n = len(pattern)
print pattern
pattern_str = ', '.join(pattern)
print pattern_str
for x in range(0, n):
    if re.search(r'\bType I\b', pattern_str):
        print "Hello Type I"
    elif re.search(r'\bType II\b', pattern_str):
        print "Hello Type II"
    else:
        print "An error has occured"

The desired output should be:

Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II

But I'm not getting the desired output. My current output is:

Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I

Can someone point out the problem? I suspect it has to be something to do with the list to str conversion. I have managed to solve the problem using the following code:

for x in pattern:
    if re.search(r'\bType I\b', x):
        print "Hello Type I"
    elif re.search(r'\bType II\b', x):
        print "Hello Type II"
    else:
        print "An error has occured"   

But I would like to know why my first code didn't work and how can I make it work. Any help is appreciated

like image 840
TheEmperor Avatar asked Feb 02 '26 18:02

TheEmperor


1 Answers

You're joining the whole list into a single string, then testing that a whole bunch of times. Instead, what you want is to test each string in the list like

for pattern_str in pattern:
    if re.search(r'\bType I\b', pattern_str):
        print "Hello Type I"
    elif re.search(r'\bType II\b', pattern_str):
        print "Hello Type II"
    else:
        print "An error has occured"

so you are searching each pattern, one at a time

like image 72
Eric Renouf Avatar answered Feb 04 '26 06:02

Eric Renouf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!