tags:

views:

40

answers:

2

I want to use a variable in a regex, like this:

variables = ['variableA','variableB']

for i in range(len(variables)):
    regex = r"'('+variables[i]+')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'"
    pattern_variable = re.compile(regex)
    match = re.search(pattern_variable, line)

The problem is that python adds an extra backslash character for each backslash character in my regex string (ipython), and makes my regex invalid:

In [76]: regex
Out[76]: "'('+variables[i]+')[:|=|\\(](-?\\d+(?:\\.\\d+)?)(?:\\))?'"

Any tips on how I can avoid this?

+1  A: 

There is no problem there. What you're seeing is the output of the repr() of the string. Since the repr is supposed to be more-or-less reversible back into the original object, it doubles up all backslashes, as well as escaping the type of quote used at the ends of the repr.

Ignacio Vazquez-Abrams
+2  A: 

No, it only displays extra backslashes so that the string could be read in again and have the correct number of backslashes. Try

print regex

and you will see the difference.

mhagger
Thanks! This seems to work fine. Maybe I should just delete this post, since it's not that important of a question?