简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM