如果我在变量中包含以下文本,则能说出"NetName:"
并返回"LVLT-GOGL-8-8-8"
的最佳方法是什么?
NetRange: 8.8.8.0 - 8.8.8.255
CIDR: 8.8.8.0/24
NetName: LVLT-GOGL-8-8-8
NetHandle: NET-8-8-8-0-1
Parent: LVLT-ORG-8-8 (NET-8-0-0-0-1)
NetType: Reallocated
NetType: Reallocated
OriginAS:
Organization: Google Inc. (GOGL)
RegDate: 2014-03-14
Updated: 2014-03-14
Ref: http://whois.arin.net/rest/net/NET-8-8-8-0-1
最佳答案
您可以使用正则表达式,在这种情况下,re.search可以完成工作:
>>> s="""NetRange: 8.8.8.0 - 8.8.8.255
...
... CIDR: 8.8.8.0/24
...
... NetName: LVLT-GOGL-8-8-8
...
... NetHandle: NET-8-8-8-0-1
...
... Parent: LVLT-ORG-8-8 (NET-8-0-0-0-1)
...
... NetType: Reallocated
...
... NetType: Reallocated
...
... OriginAS:
...
... Organization: Google Inc. (GOGL)
...
... RegDate: 2014-03-14
...
... Updated: 2014-03-14
...
... Ref: http://whois.arin.net/rest/net/NET-8-8-8-0-1"""
>>> import re
>>> re.search(r'NetName:\s+(.*)',s).group(1)
'LVLT-GOGL-8-8-8'
或者,您可以遍历拆分后的字符串并使用生成器表达式:
>>> next(line.split()[-1] for line in s.split('\n') if 'NetName:' in line)
'LVLT-GOGL-8-8-8'