views:

919

answers:

2

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. "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!

+9  A: 

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

Greg Hewgill
A: 

Thanks for the helpful comments - unfortunately, I cannot add comments myself (requires 50 reputation). Will stick to the conventions next time. (Though I'm not sure what the "community wiki" checkbox is for... )

What's wrong with regular exceptions?

Making regular users understand simple wildcards is no big deal, but most are never gonna understand RegEx (for example, they might end up wondering why "x*z" matches "xxz", not "xyz").