Python 等同于 Tcl 的 "string match"
Python equivalent to the Tcl's "string match"
我正在寻找等同于 Tcl 的 string match 操作的 Python。具体来说,我想正确处理特殊序列(*、? 和 [chars])。
例如,给定三个 Python 字符串:
expected = 'Foo? Bar* Tar'
actual1 = 'Foo2 Barfluff Tar'
actual2 = 'Foo Bar Tar'
匹配操作 match(expected,actual1)
应该 return 为真,但是 match(expected,actual2)
应该 return 为假。
非常感谢!
你想要the fnmatch
module。 re
提供功能强大的正则表达式,而 fnmatch
执行有限的 shell 风格的 globbing 通配符匹配。
对于区分大小写的匹配,很简单:
>>> fnmatch.fnmatchcase(actual1, expected)
True
>>> fnmatch.fnmatchcase(actual2, expected)
False
如果您想遵循操作系统的区分大小写规则(即在 Windows 上不区分大小写,在大多数其他操作系统上区分大小写),您可以使用普通的 fnmatch.fnmatch
来调用自动区分大小写归一化。
我正在寻找等同于 Tcl 的 string match 操作的 Python。具体来说,我想正确处理特殊序列(*、? 和 [chars])。
例如,给定三个 Python 字符串:
expected = 'Foo? Bar* Tar'
actual1 = 'Foo2 Barfluff Tar'
actual2 = 'Foo Bar Tar'
匹配操作 match(expected,actual1)
应该 return 为真,但是 match(expected,actual2)
应该 return 为假。
非常感谢!
你想要the fnmatch
module。 re
提供功能强大的正则表达式,而 fnmatch
执行有限的 shell 风格的 globbing 通配符匹配。
对于区分大小写的匹配,很简单:
>>> fnmatch.fnmatchcase(actual1, expected)
True
>>> fnmatch.fnmatchcase(actual2, expected)
False
如果您想遵循操作系统的区分大小写规则(即在 Windows 上不区分大小写,在大多数其他操作系统上区分大小写),您可以使用普通的 fnmatch.fnmatch
来调用自动区分大小写归一化。