下面是一个网络设备路由表:
destination nexthop metric flags interface
0.0.0.0/0 192.168.86.1 10 A S ethernet1/1
10.1.1.0/26 192.168.86.81 10 A S ethernet1/1
1.1.1.1/32 192.168.86.191 0 A C ethernet1/1
如何使用regex将字符串与格式网络/子网掩码(即本例中的0.0.0.0/0, 10.1.1.0/26, 1.1.1.1/32
(匹配?我尝试了以下方法。它不起作用:
import re
ip_with_mask = re.search(r'((2[0-5]|1[0-9]|[0-9])?[0-9].){3}((2[0-5]|1[0-9]|[0-9])?[0-9])/(^[1-9]$|^[1-2][0-9]$|^3[0-2]$)', oneline).group()
((2[0-5]|1[0-9]|[0-9])?[0-9].){3}((2[0-5]|1[0-9]|[0-9])?[0-9])
是ip地址。/位于网络和子网掩码之间。^[0-9]$|^[1-2][0-9]$|^3[0-2]
$是0-32子网掩码。
这个正则表达式有什么问题?
我不会在这里使用regex。您有一个固定宽度的格式,为什么不尝试使用工具(例如Python(为您解析该格式呢?
试试这个:
import io
import pandas
# You can also read this from file, I'm using an in-memory file just for demo purposes
table = io.StringIO(
"""destination nexthop metric flags interface
0.0.0.0/0 192.168.86.1 10 A S ethernet1/1
10.1.1.0/26 192.168.86.81 10 A S ethernet1/1
1.1.1.1/32 192.168.86.191 0 A C ethernet1/1
"""
)
# Read a dataframe from a Fixed Width Format (fwf)
df: pandas.DataFrame = pandas.read_fwf(table)
# Show as CSV
print(df.to_csv(index=False))
输出:
destination,nexthop,metric,flags,interface
0.0.0.0/0,192.168.86.1,10,A S,ethernet1/1
10.1.1.0/26,192.168.86.81,10,A S,ethernet1/1
1.1.1.1/32,192.168.86.191,0,A C,ethernet1/1
以下正则表达式有效:
([2][5][0-5].|[2][0-4][0-9].|[0-1]?[0-9]?[0-9].){3}([2][5][0-5]|[2][0-4][0-9]|[0-1]?[0-9]?[0-9])/([3][0-2]|[2][0-9]|[1][0-9]|[0-2])