简体   繁体   中英

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

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, eg "foo bar baz")

This seems like a common issue, so I wonder whether there's a ready-made solution for it.

Any help would be greatly appreciated!

你可以试试fnmatch模块,它有一个类似shell的通配符语法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM