How to use a variable inside a regular expression?

后端 未结 10 2144
青春惊慌失措
青春惊慌失措 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:47

    You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.

    if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
        # Successful match**strong text**
    else:
        # Match attempt failed
    

提交回复
热议问题