我想从“ip addr”命令的stdout中提取ip地址。我已经拥有了活动设备的名称(“wlp3s0”)。
我在regex101.com和it seems to work fine上测试了我的正则表达式。
但是当在Python 2.7中执行时,它只返回整个块而不是ip。
IP_RE = re.compile(r"(?<=wlp3s0:)(?:.*inet\s)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", re.DOTALL)
match = re.search(IP_RE, output_str)
if match:
print match.group()
这是python脚本的输出:
<BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether a4:4e:31:56:61:68 brd ff:ff:ff:ff:ff:ff
inet 172.16.58.158
My Regex:
/(?<=wlp3s0:)(?:.*inet\s)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/s
文字字符串:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: wlp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether a4:4e:31:56:61:68 brd ff:ff:ff:ff:ff:ff
inet 172.16.58.158/22 brd 172.16.59.255 scope global dynamic wlp3s0
valid_lft 85107sec preferred_lft 85107sec
inet6 fe80::a64e:31ff:fe56:6168/64 scope link
valid_lft forever preferred_lft forever
3: enp0s25: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
link/ether 3c:97:0e:c4:2b:0b brd ff:ff:ff:ff:ff:ff
答案 0 :(得分:3)
match.group()
always returns the entire match if called without arguments - 如果您只想要第一个捕获组的内容,则需要使用match.group(1)
。
答案 1 :(得分:0)
group(1)
会给你的愿望结果:
re.search(IP_RE, output_str).group(1)
'172.16.58.158'