[英]Python equivalent to the Tcl's “string match”
I am looking for Python equivalent to the Tcl's string match operation. 我正在寻找与Tcl的字符串匹配操作等效的Python。 Specifically, I would like to handle correctly the special sequences (*, ?, and [chars]).
具体来说,我想正确处理特殊序列(* 、?和[chars])。
For example, given three Python strings: 例如,给定三个Python字符串:
expected = 'Foo? Bar* Tar'
actual1 = 'Foo2 Barfluff Tar'
actual2 = 'Foo Bar Tar'
the match operation match(expected,actual1)
should return true, but match(expected,actual2)
should return false. 匹配操作
match(expected,actual1)
应该返回true,但是match(expected,actual2)
应该返回false。
Thanks a lot! 非常感谢!
You want the fnmatch
module . 您需要
fnmatch
模块 。 While re
provides full powered regular expressions, fnmatch
performs the limited, shell-style globbing wildcard matching you're looking for. 尽管
re
提供了完整的功能强大的正则表达式,但fnmatch
会执行您要查找的有限的,外壳样式的通配符匹配。
For a case sensitive match, it's as simple as: 对于区分大小写的匹配,它很简单:
>>> fnmatch.fnmatchcase(actual1, expected)
True
>>> fnmatch.fnmatchcase(actual2, expected)
False
If you want to follow the operating system's case sensitivity rules (that is, insensitive on Windows, sensitive on most other operating systems), you'd use plain fnmatch.fnmatch
to invoke automatic case normalization. 如果要遵循操作系统的区分大小写规则(即在Windows上不区分大小写,在大多数其他操作系统上敏感),则可以使用普通的
fnmatch.fnmatch
来调用自动区分大小写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.