Linda
Linda

Reputation: 29

Using Variables instead of pattern in Regular Expression

I am fairly new to python. I have searched several forums and have not quite found the answer.

I have a list defined and would like to search a line for occurrences in the list. Something like

import re
list = ['a', 'b', 'c']

for xa in range(0, len(list)):
m = re.search(r, list[xa], line):
if m:
    print(m)

Is there anyway to pass the variable into regex?

Upvotes: 1

Views: 53

Answers (2)

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

You can build the variable into the regex parameter, for example:

import re
line = '1y2c3a'
lst = ['a', 'b', 'c']
for x in lst:
    m = re.search('\d'+x, line)
    if m:
        print m.group()

Output:

3a
2c

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

yep, you could do like this,

for xa in range(0, len(lst)):
    m = re.search(lst[xa], line)
    if m:
        print(m.group())

Example:

>>> line = 'foo bar'
>>> import re
>>> lst = ['a', 'b', 'c']
>>> for xa in range(0, len(lst)):
        m = re.search(lst[xa], line)
        if m:
            print(m.group())


a
b

Upvotes: 1

Related Questions