如何解决Python匹配子字符串中的字符串
我正在编写一个程序来获取一个 json 格式的文件并创建一个代理 PAC 文件。我遇到的挑战之一是 json 文件包含组织不整齐的混合数据。我想总结一下数据:
输入数据:
www.example.com
*.example.com
example.com
myserver.example.com
server.*.example2.com
server.mydomain1.example2.com
server.mydomain2.example2.com
server.mydomain3.example2.com
example2.com
输出数据:
*.example.com
example.com
server.*.example2.com
example2.com
我试图找到最python的方式来总结数据。有任何想法吗?我想过使用正则表达式来帮助进行模式匹配,但我想它们很快就会变得复杂?
解决方法
我只能想出一个相当混乱的方法来做到这一点,但我会尝试用评论来解释。
import re
l = ["www.example.com","*.example.com","example.com","myserver.example.com","server.*.example2.com","server.mydomain1.example2.com","server.mydomain2.example2.com","server.mydomain3.example2.com","example2.com"]
# Something can only summarize if it contains a wildcard. Otherwise it won't represent the other elements in the list
summarizable = [domain for domain in l if "*" in domain]
[url for url in l
if not bool( # check to see if url is not represented by any of the wildcards
[1 for summary in summarizable # escape the .,replace * with re wildcard (.*)
if bool(re.match(summary.replace('.','\.').replace('*','.*'),url)) ])] + summarizable
返回
['example.com','example2.com','*.example.com','server.*.example2.com']
此解决方案的警告:如果您有两个可以相互汇总的通配符网址,它们都会出现在最终输出中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。