python-实现路径通配符匹配

实现匹配形如 D:/test/*abc.txt 的路径通配符

输入:一个包含通配符的路径字符串,例如 D:/test/*abc.txt

输出:匹配所有符合条件的文件路径,例如 D:/test/123abc.txtD:/test/456abc.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import fnmatch
from pathlib import Path

from rich.console import Console

console = Console()

def wildcard_match(path: Path, pattern: str) -> bool:
"""
基于文件名/目录名的通配符匹配(支持*、?等通配符)

参数:
path: Path对象,待匹配的文件/目录路径
pattern: 字符串,通配符匹配模式(如test*、abc?等)

返回:
bool: 匹配结果,True表示path的名称符合pattern,False反之
"""
# fnmatch.fnmatch仅匹配路径的最后一部分(名称),而非完整路径
return fnmatch.fnmatch(path.name, pattern)


def backtrack_match(parts: list[str]) -> list[Path]:
"""
基于回溯法递归查找符合层级通配符规则的目录路径

核心逻辑:
1. 将目标路径拆分为多个层级部分(如['D:/', '转移文件', 'test*', 'test*'])
2. 从根路径开始,逐层递归匹配每个层级的通配符规则
3. 匹配成功则进入下一层级,匹配失败则回溯到上一层级继续探索其他可能
4. 收集所有完整匹配的路径并返回

参数:
parts: 路径层级列表,每个元素为对应层级的路径/通配符规则
示例:['D:/', '转移文件', 'test*', 'test*'] 表示查找
D:/转移文件/以test开头的目录/以test开头的目录

返回:
list[Path]: 所有符合层级通配符规则的完整路径列表(Path对象)
"""
# 存储所有匹配成功的完整路径
all_paths: list[Path] = []

# 维护当前递归的路径状态(存储各层级目录名),初始化为根路径部分
current_path_state: list[str] = [parts[0]]

def backtrack(index: int):
"""
递归回溯的核心内部函数

参数:
index: 当前正在匹配的路径层级索引(对应parts列表的下标)
"""
now_looking_at = Path('/'.join(current_path_state))

# 递归终止条件:已匹配完所有层级,找到完整有效路径
if index == len(parts):
# 将当前路径状态拼接为完整Path对象并加入结果列表
all_paths.append(now_looking_at)
# 控制台输出找到的有效路径(绿色加粗)
console.print(f"[bold green] Answer: {now_looking_at.as_posix()}")
return

# 拼接当前已匹配的路径,用于遍历子目录
console.print(f"Checking path: {now_looking_at.as_posix()}")

# 遍历当前路径下的所有子项(文件/目录)
for child in now_looking_at.iterdir():
# 仅处理目录,且目录名符合当前层级的通配符规则
if child.is_dir() and wildcard_match(child, parts[index]):
console.print(f' Valid path found: {child.as_posix()}')
# 将符合规则的子目录名加入当前路径状态
current_path_state.append(child.name)
# 递归匹配下一层级
backtrack(index + 1)
# 回溯:移除最后加入的目录名,回到上一层级继续探索其他子目录
current_path_state.pop()
console.print(f" Backtracking to: {now_looking_at.as_posix()}")

# 从层级索引1开始递归(索引0是根路径,已初始化到current_path_state)
backtrack(1)
return all_paths


def separate_path(p: str) -> list[str]:
"""
将路径字符串拆分为层级列表
"""
p = p.replace('\\', '/')
lst = list(p.split('/'))
if lst and ':' in lst[0]:
# windows drive, add a /
# 对于windows的盘符,需要在盘符后添加一个 /,否则返回 D: 算法无法识别为合法路径
lst[0] += '/'

return lst

  1. 核心功能:backtrack_match 通过回溯递归逐层匹配路径层级的通配符规则,wildcard_match 是底层的通配符匹配工具函数;
  2. 关键逻辑:递归终止条件是匹配完所有路径层级,回溯操作通过 current_path_state.pop() 实现,确保探索所有可能的路径分支;
  3. 输出特性:使用 rich 库美化控制台输出。

python-实现路径通配符匹配
https://taylorandtony.github.io/2026/03/06/python-实现路径通配符匹配/
作者
TaylorAndTony
发布于
2026年3月6日
许可协议