如何在正则expression式中使用variables?

我想在regex使用一个variable ,我怎样才能在Python实现这一点?

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

你必须build立一个string的正则expression式:

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

注意re.escape的使用,这样如果你的文本有特殊的字符,就不会被解释为这样。

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

这将把TEXTO中的内容作为string插入到正则expression式中。

 rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO) 

我需要search相似的用户名,Ned Batchelder说的是非常有用的。 不过,当我使用re.compile创build我的重新search词时,我发现我有更清晰的输出:

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

输出可以使用以下方式打印:

 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. 

我发现通过串联多个较小的模式来构build正则expression式模式非常方便。

 import re string = "begin:id1:tag:middl:id2:tag:id3:end" re_str1 = r'(?<=(\S{5})):' re_str2 = r'(id\d+):(?=tag:)' re_pattern = re.compile(re_str1 + re_str2) match = re_pattern.findall(string) print(match) 

输出:

 [('begin', 'id1'), ('middl', 'id2')] 

我同意以上所述,除非:

sys.argv [1]类似于“鸡\ d {2} – \ d {2}一个重要的\ s锚”

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

你不想使用re.escape,因为在这种情况下,你会喜欢它像一个正则expression式

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