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

Python 如何在正则表达式中使用变量?,python,regex,python-3.x,variables,escaping,Python,Regex,Python 3.x,Variables,Escaping,我想在regex中使用变量,如何在Python中实现这一点 TEXTO = sys.argv[1] if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE): # Successful match else: # Match attempt failed rx=r'\b(?if re.search(r)\b(?必须将正则表达式构建为字符串: TEXTO = sys.argv[1] my_regex = r"\

我想在
regex
中使用
变量
,如何在
Python
中实现这一点

TEXTO = sys.argv[1]

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

rx=r'\b(?
if re.search(r)\b(?必须将正则表达式构建为字符串:

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
,这样,如果文本中有特殊字符,它们就不会被解释为特殊字符。

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

sys.argv[1]
有点像
Chicken\d{2}-\d{2}An\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
TEXTO=sys.argv[1]

如果re.search(r“\b(?我需要搜索彼此相似的用户名,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.

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

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)

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

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

您可以使用
format
grammer-suger尝试其他用法:

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

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

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

由于评论中有一些关于如何处理特殊角色的问题,我想扩展我的回答:

原始字符串('r'):

在处理正则表达式中的特殊字符时,您必须理解的一个主要概念是区分字符串文字和正则表达式本身。下面对此进行了详细说明:

简言之:

假设不在
TEXTO
之后查找单词边界
\b
,而是要匹配字符串
\boundary
。您必须编写:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")
if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")
这仅仅是因为我们使用的是原始字符串(regex前面有'r'),否则我们必须在regex中写“\\\\boundary”(四个反斜杠)。此外,如果没有'\r',\b'将不再转换为单词边界,而是转换为退格

关于逃逸

基本上是在任何特殊字符前面加上退格。因此,如果您希望在TEXTO中使用特殊字符,则需要编写:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")
if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")
注意:对于任何版本>=python 3.7:
%
`
,都不会转义。只有正则表达式中有意义的特殊字符仍然会转义。
自3.3以来不会转义。(s)

花括号:

如果要使用f字符串在正则表达式中使用量词,则必须使用双大括号。假设要匹配TEXTO,后跟两位数字:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")
更多示例

我已经给我们做了配置 使用流文件

"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)

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


regex\u str=r'\b(?使用字符串连接如果变量先执行怎么办?
r'+foo+'bar'
?@deed02392
r'
如果执行
re.escape(foo)操作,则不需要
,您无论如何都应该这样做。实际上,我认为
re
会将给定的任何内容解释为unicode字符串,而不管您是否使用前缀
r
。format()是否也可以代替re.escape或is re.escape()必要吗?@praxiteles你找到答案了吗?我不确定这是否有效,我需要一个变量是其中一部分的组。下面的其他答案看起来更直观,不要将正则表达式分解成几个表达式。从2020年开始,这是在正则表达式中使用变量的最简单和最具python风格的方法。这是defini哇,有人能解释一下“rf”的意义吗here@HarshaReddy:“r”:此字符串是原始字符串:如果不使用它,“\b”将转换为退格字符().f'告诉python这是一个“f-string”,上面的s.链接,并使您能够将变量写入花括号中如何在f-string中写入量词:
fr“foo{{1,5}”
(大括号加倍)如果我在正则表达式中使用{4}来表示我只想要前面的4个,这不是一个问题吗?
data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)