Python 从字符串中拉出字符串(拆分?)
我有一个字符串-示例如下:Python 从字符串中拉出字符串(拆分?),python,Python,我有一个字符串-示例如下: g0/1 192.168.1.1 YES NVRAM up up 我想从中提取IP地址,但不是最后一个八位组。我想拉192.168.1。这样以后就可以使用了 我认为我需要使用split,但不确定如何实现这一点 output = ' g0/1 192.168.1.1 YES NVRAM up up'
g0/1 192.168.1.1 YES NVRAM up up
我想从中提取IP地址,但不是最后一个八位组。我想拉192.168.1。这样以后就可以使用了
我认为我需要使用split,但不确定如何实现这一点
output = ' g0/1 192.168.1.1 YES NVRAM up up'
ouput = ouput.split('192.168.1.',)
你可以用
编辑:从match()
更改为search()
,因为match()
只查看字符串的开头
另外,假设您希望对多个字符串执行此操作,则可以使用函数,该函数将返回正则表达式的所有匹配组的列表
> import re
> input_string = "g0/1 192.168.1.1 YES NVRAM up up"
> outputs = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.', input_string)
> print(outputs)
['192.168.1.']
只需使用split()
我谦恭地说,正则表达式对于这项任务来说太沉重了。我似乎陷入了使用正则表达式的陷阱,即使在没有必要的时候。
> import re
> input_string = "g0/1 192.168.1.1 YES NVRAM up up"
> outputs = re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.', input_string)
> print(outputs)
['192.168.1.']
>>> output.split()[1].rsplit(".", 1)[0]
'192.168.1'