How to use a variable inside a regular expression?

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

    You have to build the regex as a string:

    TEXTO = sys.argv[1]
    my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"
    
    if re.search(my_regex, subject, re.IGNORECASE):
        etc.
    

    Note the use of re.escape so that if your text has special characters, they won't be interpreted as such.

提交回复
热议问题