我使用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))
只有在定义带有大量反斜杠的字符串时才需要
r
前缀,因为regex和Python字符串语法都将含义附加到反斜杠上。r'..'
只是另一种语法,它使使用regex模式变得更容易。您没有来使用r'..'
原始字符串。有关详细信息,请参见Python regex howto中的The backslash plague。你知道吗所有这一切都意味着,当已经有字符串值时,您当然不需要使用
r
前缀。正则表达式模式只是一个字符串值,您可以使用普通的字符串格式或串联技术:我没有在上面的字符串文字中使用
r
,因为表达式中没有引起问题的\
反斜杠。你知道吗如果} function 。
lattice_type
值可能包含正则表达式元字符,例如.
或?
或[
等,则您可能需要在lattice_type
值上使用^{re.escape()
转义这些元字符,以便只匹配文本:相关问题 更多 >
编程相关推荐