![](/img/trans.png)
[英]How can I support wildcards in user-defined search strings in Python?
[英]How can I support * in user-defined search strings in python?
這個問題與這個堆棧溢出問題有關:
但是我只需要支持通配符而不是? 或通過fnmatch獲得的[seq]功能。 由於無法從fnmatch中刪除該功能,是否有另一種方法可以做到這一點?
我需要這樣的用戶定義的字符串: site.*.com/sub/
與此匹配: site.hostname.com/sub/
沒有所有添加的功能? 和[]
您可以使用split,re.escape和'^ $'從搜索字符串中編譯一個正則表達式。
import re
regex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')
如果它只是一個星號,並且您需要搜索字符串代表整個匹配的字符串,則可以這樣做:
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!"
否則,構建像Tobu建議的正則表達式可能是最好的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.