How to use a variable inside a regular expression?

后端 未结 10 2062
青春惊慌失措
青春惊慌失措 2020-11-22 03:29

I\'d like to use a variable inside a regex, how can I do this in Python?

TEXTO = sys.argv[1]

if re.search(r\"\\b(?=\\         


        
10条回答
  •  余生分开走
    2020-11-22 03:37

    I agree with all the above unless:

    sys.argv[1] was something like Chicken\d{2}-\d{2}An\s*important\s*anchor

    sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"
    

    you would not want to use re.escape, because in that case you would like it to behave like a regex

    TEXTO = sys.argv[1]
    
    if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
        # Successful match
    else:
        # Match attempt failed
    

提交回复
热议问题