【发布时间】:2019-02-21 14:14:16
【问题描述】:
我正在寻找与 Tcl 的 string match 操作等效的 Python。具体来说,我想正确处理特殊序列(*、? 和 [chars])。
例如,给定三个 Python 字符串:
expected = 'Foo? Bar* Tar'
actual1 = 'Foo2 Barfluff Tar'
actual2 = 'Foo Bar Tar'
匹配操作match(expected,actual1)应该返回true,但match(expected,actual2)应该返回false。
非常感谢!
【问题讨论】:
-
您正在寻找正则表达式(模块
re)。 -
@DYZ:实际上,对于类似 glob 的模式匹配,
fnmatch更合适。它实际上是在后台使用re实现的(通过缓存,重复使用相同的 glob 模式不需要一遍又一遍地重新转换/重新编译等效的正则表达式),但它直接与 shell 通配符模式一起使用,无需重写它们成正则表达式。
标签: python string tcl matching glob