How can I support wildcards in user-defined search

2020-07-08 06:11发布

问题:

Is there a simple way to support wildcards ("*") when searching strings - without using 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

(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.

Any help would be greatly appreciated!

回答1:

You could try the fnmatch module, it's got a shell-like wildcard syntax.