如何在正则表达式中使用变量?

时间:2011-08-03 17:59:42

标签: python regex python-3.x variables escaping

我想在variable内使用regex,如何在Python中执行此操作?

TEXTO = sys.argv[1]

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

11 个答案:

答案 0 :(得分:236)

您必须将正则表达式构建为字符串:

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的使用,以便如果您的文字有特殊字符,则不会将其解释为此类字符。

答案 1 :(得分:40)

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

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

答案 2 :(得分:31)

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

答案 3 :(得分:3)

我同意以上所有内容,除非:

sys.argv[1]类似于Chicken\d{2}-\d{2}An\s*important\s*anchor

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

答案 4 :(得分:3)

我发现通过将多个较小的模式串联起来构建正则表达式模式非常方便。

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')]

答案 5 :(得分:2)

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

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.

答案 6 :(得分:1)

您可以使用format语法suger尝试另一种用法:

re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)  

答案 7 :(得分:1)

从python 3.6开始,您还可以使用Literal String Interpolation,“ f-strings”。在您的情况下,解决方案是:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

答案 8 :(得分:0)

您也可以为此使用format关键字。Format方法将{}占位符替换为您作为参数传递给format方法的变量。

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

答案 9 :(得分:0)

更多示例

我有configus.yml 带有流文件

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

在我使用的python代码中

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

答案 10 :(得分:0)

这是您可以使用的另一种格式(在 python 3.7 上测试)

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

我发现当您不能将 {} 用作变量时它很有用(此处替换为 %s