How to use a variable inside a regular expression ?

How to use a variable inside a regular expression ?

Asked on December 26, 2018 in Regex.
Add Comment


  • 2 Answer(s)

    To build the regex as a string,use this:

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

    Use re.escape to text has special characters.

    Answered on December 26, 2018.
    Add Comment

    Use a variable inside a regular expression by this method:

    if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):
    
    

    Above code will insert TEXTO into the regex as a string.

    Answered on December 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.