无法从XML文件提取32位字符串的Python代码问题
问题:XML文件中32位字符串提取失败,返回空列表
我编写了一段Python代码,功能为让用户指定目录后遍历其中的.xml文件,从每个文件中提取长度为32位的字符串(仅要求长度,内容无关)。我使用regex模块实现,但运行时程序能找到所有XML文件,string_recovery函数却仅返回空列表,而我已确认XML文件中确实存在32位字符串。
原代码如下:
import os import re import tkinter as tk from tkinter import filedialog def string_recovery(data): short_string = re.compile(r"^[a-zA-Z0-9\-._]{32}$") strings = re.findall(short_string, data) print(strings) def xml_search(directory): xml_files = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(".xml"): xml_files.append(os.path.join(root, file)) print("The following XML files have been found.") print(xml_files) for xml_file in xml_files: with open(xml_file, "r") as f: string_recovery(f.read()) def key_finder(): directory = filedialog.askdirectory() xml_search(directory) key_finder()
解决方案
修改string_recovery函数中的正则表达式,去掉行锚点^和$:
def string_recovery(data): # 去掉^和$,允许字符串出现在文本任意位置 short_string = re.compile(r"[a-zA-Z0-9\-._]{32}") strings = re.findall(short_string, data) print(strings)
如果需要确保匹配的是独立的32位字符串(避免从更长的字符序列中截取32位片段),可以添加单词边界\b(注意:如果字符串包含.或-这类非单词字符,\b可能不生效,此时可根据XML实际结构调整):
short_string = re.compile(r"\b[a-zA-Z0-9\-._]{32}\b")
原因说明
原正则表达式中的^表示行开头,$表示行结尾,这要求匹配的32位字符串必须单独占据一整行。但XML文件中的32位字符串通常嵌套在标签内容中(比如<value>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</value>),并非单独成行,因此无法被匹配到。去掉这两个锚点后,正则会在整个文本内容中搜索符合长度和字符范围的32位字符串,就能正确提取目标内容。
内容的提问来源于stack exchange,提问作者LHenne300
相关产品推荐
相关产品推荐

