开发者

Use string as input to re.compile

开发者 https://www.devze.com 2022-12-23 22:44 出处:网络
I want to use a variable in a regex, like this: variables = [\'variableA\',\'variableB\'] for i in range(len(variables)):

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 st开发者_运维问答ring (ipython), and makes my regex invalid:

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

Any tips on how I can avoid this?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消