0

This question is related to this stack overflow question:

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 []

Community
  • 1
  • 1
Robbie
  • 892
  • 2
  • 7
  • 19

2 Answers2

3

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
  • 24,771
  • 4
  • 91
  • 98
  • 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 Jan 11 '10 at 17:32
1

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.

Community
  • 1
  • 1
balpha
  • 50,022
  • 18
  • 110
  • 131