繁体   English   中英

如何从 Python 中的 FQDN 中提取主机名和(子)域?

[英]How do I extract the hostname and the (sub)domain from a FQDN in Python?

我正在尝试编写一个脚本,该脚本将采用 FQDN 并为我提供主机名和(子)域。

我能够获取主机名,但我不知道如何获取整个域,包括任何子域。

请注意,这些域和子域将是内部域,而不是公共域。

import re 

words = "testing.something.thisdomain.com"
 

stuff = re.match(r"(.+?)(?=\.)", words)

print(stuff.group(1))

即使您的 fqdn 没有任何子域,这也有效

代码:

fqdn = "testing.something.thisdomain.com"
tld, domain, *sub_domains = fqdn.split(".")[::-1]
print(tld,domain,sub_domains)

Output:

com thisdomain ['something', 'testing']

我们不能只在字符串上使用 split 并打印您需要的部分,而不是做一堆花哨的正则表达式吗?

words = "testing.something.thisdomain.com"
stuff = words.split(".")
print(stuff[1])

暂无
暂无

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

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