简体   繁体   中英

How can I support * in user-defined search strings in python?

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

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('*')) + '$')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM