Reputation: 29
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
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
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