tags:

views:

77

answers:

2

This question is related to this stack overflow question:

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

But I need to only support the wildcards and not the ? or the [seq] functionality that you get with fnmatch. Since there is no way to remove that functionality from fnmatch, is there another way of doing this?

I need a user defined string like this: site.*.com/sub/
to match this: site.hostname.com/sub/

Without all the added functionality of ? and []

+3  A: 

You could compile a regexp from your search string using split, re.escape, and '^$'.

import re
regex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')
Tobu
This was perfect. I was trying to figure out a way to escape all the little bits of re, but thought it would be really complicated.
Robbie
+1  A: 

If its just one asterisk and you require the search string to be representing the whole matched string, this works:

searchstring = "site.*.com/sub/"
to_match = "site.hostname.com/sub/"

prefix, suffix = searchstring.split("*", 1)

if to_match.startswith(prefix) and to_match.endswith(suffix):
    print "Found a match!"

Otherwise, building a regex like Tobu suggests is probably best.

balpha
Yea, it's user generated so I could be anything.
Robbie