How can I support wildcards in user-defined search strings in Python?

不想你离开。 提交于 2020-01-01 09:12:17

问题


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.



来源:https://stackoverflow.com/questions/238600/how-can-i-support-wildcards-in-user-defined-search-strings-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!