我想在正则表达式中使用一个变量,我如何在Python中做到这一点?

TEXTO = sys.argv[1]

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

当前回答

我需要搜索彼此相似的用户名,Ned Batchelder说的非常有用。然而,当我使用re.compile创建我的re搜索项时,我发现我有更清晰的输出:

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.

其他回答

我需要搜索彼此相似的用户名,Ned Batchelder说的非常有用。然而,当我使用re.compile创建我的re搜索项时,我发现我有更清晰的输出:

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.
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)

下面是你可以使用的另一种格式(在python 3.7上测试)

regex_str = r'\b(?< \ \w)%s\b(

我发现当你不能使用{}变量(这里替换为%s)时,它很有用。

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

这将把TEXTO中的内容作为字符串插入到正则表达式中。

我同意以上所有观点,除非:

sys。argv[1]有点像Chicken\d{2}-\d{2}一个\s*重要的\s*锚

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

你不会想要使用re.escape,因为在这种情况下,你希望它表现得像一个正则表达式

TEXTO = sys.argv[1]

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