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!

3
  • 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. Commented Oct 26, 2008 at 21:03
  • What's wrong with regular exceptions? Commented Oct 26, 2008 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? Commented Apr 27, 2011 at 5:01

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.