How to use a variable inside a regular expression?

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

    I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:

    pattern = re.compile(r"("+username+".*):(.*?):(.*?):(.*?):(.*)"
    matches = re.findall(pattern, lines)
    

    Output can be printed using the following:

    print(matches[1]) # prints one whole matching line (in this case, the first line)
    print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.
    

提交回复
热议问题