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

问题描述 投票:0回答:1

我有以下 Python 代码,它使用正则表达式来检测模式。该模式有 3 组,其中一组是存储在列表中的一系列关键字,因此正则表达式有一个迭代所有列表项的变量。尽管它适用于一些小测试文件以及 regex101,但它不会检测到任何匹配项。代码如下:

import re
import csv

with open(r'C:\Users\mike\TestRes.csv') as file_obj:
      
    reader_obj = csv.reader(file_obj, delimiter=",") 
    rcnt = 0
    for row in reader_obj: 
        strs=str(row)
        Keywords=["Doctor","Policeman","Teacher","Dentist"]
        cnt = 0        
        for i in Keywords:            
            print(rcnt,i)
            pattern = re.compile(r"(\n\w.+\n+)({re.escape(i)})(\n+\w.+\n)",re.IGNORECASE)
            for match in pattern.finditer(strs,re.MULTILINE):
                cnt += 1
                if match:
                    print(row[0],cnt,match.group(1),match.group(2),match.group(3))
                else: print("Not Found")
        rcnt += 1
    else: print("NotFound")

下图显示了存储在 csv 文件中的输入文本。第 2 组应与关键字匹配,第 1 组应与名称匹配,第 3 组应与文本描述匹配。

enter image description here

虽然它适用于某些测试文件,但当我像这样运行它时它不起作用。我没有收到任何错误消息,但它没有检测到任何匹配项。

python regex variables
1个回答
0
投票

您需要使用

fr""
而不是仅使用
"r"
作为
re.compile()
内的图案。

f
让Python可以计算
{re.escape(i)}
部分(称为f字符串),然后然后交给正则表达式来编译模式。

© www.soinside.com 2019 - 2024. All rights reserved.