如何在python中将变量用作regex?

2024-05-19 03:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用re在文件中查找单词,并将其存储为lattice_type 现在我想使用存储在lattice_type上的单词来生成另一个regex

我试着用这个方法来命名变量

pnt_grp=re.match(r'+ lattice_type + (.*?) .*',line, re.M|re.I)

这里我查找regex lattice_type=,并将group(1)存储在lattice_type

latt=open(cell_file,"r")
    for types in latt:
        line = types
        latt_type = re.match(r'lattice_type = (.*)', line, re.M|re.I)
        if latt_type:
            lattice_type=latt_type.group(1)

在这里,我想使用包含单词的变量在另一个文件中查找它,但遇到了问题

pg=open(parameters,"r")
    for lines in pg:
        line=lines
        pnt_grp=re.match(r'+ lattice_type + (.*?) .*',line, re.M|re.I)
        if pnt_grp:
            print(pnt_grp(1))

Tags: 文件refortypematchlinegroupopen
1条回答
网友
1楼 · 发布于 2024-05-19 03:39:45

只有在定义带有大量反斜杠的字符串时才需要r前缀,因为regex和Python字符串语法都将含义附加到反斜杠上。r'..'只是另一种语法,它使使用regex模式变得更容易。您没有来使用r'..'原始字符串。有关详细信息,请参见Python regex howto中的The backslash plague。你知道吗

所有这一切都意味着,当已经有字符串值时,您当然不需要使用r前缀。正则表达式模式只是一个字符串值,您可以使用普通的字符串格式或串联技术:

pnt_grp = re.match(lattice_type + '(.*?) .*', line, re.M|re.I)

我没有在上面的字符串文字中使用r,因为表达式中没有引起问题的\反斜杠。你知道吗

如果lattice_type值可能包含正则表达式元字符,例如.?[等,则您可能需要在lattice_type值上使用^{} functionre.escape()转义这些元字符,以便只匹配文本

pnt_grp = re.match(re.escape(lattice_type) + '(.*?) .*', line, re.M|re.I)

相关问题 更多 >

    热门问题