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

2 Answers 2

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('*')) + '$')
Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.