1

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?

2
  • Your question is not clear - what is the variable r ? you should describe what you're trying to do (example input + output). Commented May 3, 2015 at 2:05
  • What are you doing with the re.search? And what do you mean "search a line for occurrences in the list"? Just fyi, proper indentation is required for your for loops, and if you pass in 3 arguments to re.search, the third argument will be interpreted as a keyword argument: flags. Commented May 3, 2015 at 2:17

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thanks for your assistance. New programmers are always appreciate assistance.

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.