分段 | 正则表达式 | 解释 |
---|---|---|
0-99 | [1-9]?[0-9] |
? 表示前面[] 中的内容可以取或不取 |
100-199 | 1[0-9]{2} |
100到199的百位相同,十位个位都可以取0-9,使用{2}表示 |
200-249 | 2[0-4][0-9] |
|
250-255 | 25[0-5] |
组合表示一个255使用|
连接
([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
ip地址格式:xxx.xxx.xxx.xxx
(每个xxx表示一个0-255的数字)
观看规律发现 xxx.
重复了三次,因此用下面的表示(.
比较特殊因此需要反斜线转译)
(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}
完整的ip地址还缺少最后一个xxx
拼接上格式为
(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
使用egrep或 grep -E 不需要对(){}|
转译,而使用grep必须转译
因此博主给了如下两种方式
grep -Eo "(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"
grep -o "\(\([1-9]\?[0-9]\|1[0-9]\{2\}\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\([1-9]\?[0-9]\|1[0-9]\{2\}\|2[0-4][0-9]\|25[0-5]\)"
测试结果:
[root@master etc]#ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.0.106 netmask 255.255.255.0 broadcast 192.168.0.255
inet6 fe80::8594:34ed:d5bf:7578 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:a6:81:72 txqueuelen 1000 (Ethernet)
RX packets 3771121 bytes 321230571 (306.3 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 4390188 bytes 587011207 (559.8 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 40 bytes 3048 (2.9 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 40 bytes 3048 (2.9 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255
ether 52:54:00:99:a5:a2 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
`[root@master etc]#ifconfig |grep -Eo "(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" `192.168.0.106
255.255.255.0
192.168.0.255
127.0.0.1
255.0.0.0
192.168.122.1
255.255.255.0
192.168.122.255
`[root@master etc]#ifconfig |grep -o "\(\([1-9]\?[0-9]\|1[0-9]\{2\}\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\([1-9]\?[0-9]\|1[0-9]\{2\}\|2[0-4][0-9]\|25[0-5]\)" `192.168.0.106
255.255.255.0
192.168.0.255
127.0.0.1
255.0.0.0
192.168.122.1
255.255.255.0
192.168.122.255
效果截图