8

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!

brian d foy
  • 129,424
  • 31
  • 207
  • 592
  • For asking normal programming questions, please don't mark your question as "community wiki". Nobody (including you) gets any reputation for that kind of question. I see you're new here, so no worries, just keep that in mind for next time. – Greg Hewgill Oct 26 '08 at 21:03
  • What's wrong with regular exceptions? – Hortitude Oct 26 '08 at 21:04
  • First off, its regular **expressions**. Second, wouldn't it be easy enough to escape anything in the input that needs escaping for regex, turn `*` into `.*` and run it through the regex module? – Aaron Dufour Apr 27 '11 at 05:01

1 Answers1

14

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

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285