如何在Python的用户定义搜索字符串中支持通配符? [英] How can I support wildcards in user-defined search strings in Python?
本文介绍了如何在Python的用户定义搜索字符串中支持通配符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在搜索字符串时是否有一种简单的方法来支持通配符("*"),而无需使用RegEx?
Is there a simple way to support wildcards ("*") when searching strings - without using RegEx?
用户应该使用通配符输入搜索词,但不必处理RegEx的复杂性:
Users are supposed to enter search terms using wildcards, but should not have to deal with the complexity of RegEx:
"foo*" => str.startswith("foo")
"*foo" => str.endswith("foo")
"*foo*" => "foo" in str
(但是,当有多个搜索字词时,例如"foo bar baz",它将变得更加复杂)
(it gets more complicated when there are multiple search terms though, e.g. "foobarbaz")
这似乎是一个常见问题,所以我想知道是否有现成的解决方案.
This seems like a common issue, so I wonder whether there's a ready-made solution for it.
任何帮助将不胜感激!
推荐答案
您可以尝试 fnmatch
模块,它具有类似shell的通配符语法.
You could try the fnmatch
module, it's got a shell-like wildcard syntax.
这篇关于如何在Python的用户定义搜索字符串中支持通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文