Python 3.6.1 |正则表达式搜索具有特殊字符的文件

Python 3.6.1 | Regex Search on files with special characters

我打算做什么?

要在 Windows 文件系统上的一组文件中搜索 字母 字符串列表(大约 25K 个不同大小和扩展名的主要是纯文本文件, 最大文件大小不超过几 MB)

我是怎么做到的?

for each_file in files:
    file_read_handle = open(each_file,"rb")
    file_read_handle.seek(0) #ensure you're at the start of the file
    first_char = file_read_handle.read(1) #get the first character
    if first_char:
        file_read_content_mappd = mmap.mmap(file_read_handle.fileno(), 0, access=mmap.ACCESS_READ)
        if re.search(br'(?i)T_0008X_WEB', file_read_content_mappd):
            file_write_content = ('Text T_0008X_WEB found in {}'.format(each_file))
            file_write_handle.write(file_write_content)     
            file_write_handle.write("\n")
file_write_handle.close()

这段代码工作得很好用于在打开的文件中进行硬编码文本搜索(参见行T_0008X_WEB)在二进制模式下 ("rb") 以避免 UnicodeDecodeError: 'charmap' codec can't decode byte位置 776 中的 0x9d:字符映射到未定义 错误。

但是,当尝试搜索 值列表 时,通过用这样的变量替换硬编码值-if re.search('br\'(?i)' + regex_search_str_byte + '\'', file_read_content_mappd):, 一直面临以下问题-

  1. 使用时:re.search('br\'(?i)' + regex_search_str + '\'', file_read_content_mappd):得到错误:文件为二进制,搜索文本为字符串类型
  2. 使用时:re.search(regex_search_str_byte, file_read_content_mappd): 遇到问题:找不到匹配项,因为即使是正则表达式字符 br'(?i) 也被视为字节转换搜索文本的一部分

请求有关如何执行字节转换文本正则表达式搜索以二进制模式打开文件读取值列表的指导?

使用

re.search(regex_search_str_byte, file_read_content_mappd, flags=re.I)

re.I 标志可以作为参数传递给 re.search 方法。 br 前缀不是必需的,因为它们用于修改字符串文字,而您正在使用变量。