简体   繁体   English

如何在python中的用户定义搜索字符串中支持*?

[英]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? 如何在Python的用户定义搜索字符串中支持通配符?

But I need to only support the wildcards and not the ? 但是我只需要支持通配符而不是? or the [seq] functionality that you get with fnmatch. 或通过fnmatch获得的[seq]功能。 Since there is no way to remove that functionality from fnmatch, is there another way of doing this? 由于无法从fnmatch中删除该功能,是否有另一种方法可以做到这一点?

I need a user defined string like this: site.*.com/sub/ 我需要这样的用户定义的字符串: site.*.com/sub/
to match this: site.hostname.com/sub/ 与此匹配: 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 '^$'. 您可以使用split,re.escape和'^ $'从搜索字符串中编译一个正则表达式。

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. 否则,构建像Tobu建议的正则表达式可能是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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