Use string as input to re.compile
        Posted  
        
            by williamx
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by williamx
        
        
        
        Published on 2010-03-22T09:55:03Z
        Indexed on 
            2010/03/22
            10:01 UTC
        
        
        Read the original article
        Hit count: 502
        
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?
© Stack Overflow or respective owner