1

I have a large list of data and another list of patterns. I'm trying to filter data using the patterns. Here's my code using some sample data:

dataList = [ '4334 marked val 5656 bin', 
    '76-67-34 done this 99', 
    'bin ket AZZ3R434 pid' 
]

for data in dataList:
    regexList = [ re.search(r'val ([\d]+) bin', data),
            re.search(r'bin ket ([A-Z\d-]+)\b', data)
        ]

    for reg in regexList:
        if reg:                   #If there's a match
            #...do something...
            break

In the above code in regexlist the 're.search()' part is getting repeated again and again. I want to keep only a list of patterns, something like below:

regexList = [ 'val ([\d]+) bin',
        'bin ket ([A-Z\d-]+)\b'
    ]

And use these patterns one by one with re.search() later. I tried using eval() and exec() both, but just kept getting errors.

I would also like to know whether 'regexList' is getting created again and again under for loop?

0

2 Answers 2

2

I don't see why you would need to do this with eval/exec. Just pass the pattern to re.search inside the loop:

regexList = [
    r'val ([\d]+) bin',
    r'bin ket ([A-Z\d-]+)\b'
]
for pattern in regexList:
    if re.search(pattern, data):
        ...
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah it can be done this way. Cool. But was wondering how to do it with exec/eval.
1
dataList = [ '4334 marked val 5656 bin', 
    '76-67-34 done this 99', 
    'bin ket AZZ3R434 pid' 
]

regexList = [
         r'val ([\d]+) bin',
         r'bin ket ([A-Z\d-]+'
]
for data in dataList:
    for reg in regexList:
        if  re.search(reg,data):                   #If there's a match
            #...do something...
            break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.