【问题标题】:How can I use a variable as regex in python? [duplicate]如何在 python 中使用变量作为正则表达式? [复制]
【发布时间】:2019-06-17 07:32:41
【问题描述】:

我使用re 在文件中查找单词并将其存储为lattice_type 现在我想使用存储在lattice_type 上的单词来制作另一个正则表达式

我试过用这种方式使用变量名

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

在这里我查找正则表达式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))

【问题讨论】:

    标签: python regex


    【解决方案1】:

    r 前缀仅在定义带有大量反斜杠的字符串时才需要,因为正则表达式和 Python 字符串语法都将含义附加到反斜杠。 r'..' 只是一种替代语法,它更容易 使用正则表达式模式。您没有使用r'..' 原始字符串文字。有关更多信息,请参阅 Python regex howto 中的The backslash plague

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

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

    我没有在上面的字符串文字中使用r,因为那里的表达式中没有\ 反斜杠会导致问题。

    可能需要在您的lattice_type 值上使用re.escape() function,如果该值可能包含正则表达式元字符,例如.?[re.escape() 对此类元字符进行转义,以便仅匹配 文字

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

    【讨论】:

    • 我进行了更改,但我得到了这个:在 '_sre.SRE_Match' 对象不可调用,因为 lattice_type 是稍后搜索的匹配项。我该如何解决?
    • @JorgeCastro:如果lattice_type 是匹配对象,则使用match object method 获取字符串。如lattice_type.group()
    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2018-04-08
    • 2013-06-17
    • 2016-11-17
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多