How can I support wildcards in user-defined search

2020-07-08 06:34发布

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条回答
唯我独甜
2楼-- · 2020-07-08 06:48

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

查看更多
登录 后发表回答