假设有一个字典file_dict
,其中包含了文件名和对应的值。我们需要遍历字典中与文件名前5个数字匹配的值。
import re
file_dict = {
"12345_file1.txt": "value1",
"23456_file2.txt": "value2",
"34567_file3.txt": "value3",
"45678_file4.txt": "value4",
"56789_file5.txt": "value5",
"67890_file6.txt": "value6"
}
pattern = re.compile(r"^\d{5}")
matching_values = []
for file_name, value in file_dict.items():
if pattern.match(file_name):
matching_values.append(value)
print(matching_values)
以上代码中,我们使用了正则表达式^\d{5}
来匹配文件名前5个数字。然后,我们遍历字典中的每个键值对,如果文件名匹配成功,我们将对应的值添加到matching_values
列表中。
最后,我们打印matching_values
列表,即为与文件名前5个数字匹配的值。