Python 使用正则表达式提取网络IP地址子字符串
如何使用regex查找ip网络 范例Python 使用正则表达式提取网络IP地址子字符串,python,regex,pandas,ip-address,Python,Regex,Pandas,Ip Address,如何使用regex查找ip网络 范例 IP 234.523.213.462:321 21.236.432.123:66666 213.406.421.436:7324 我想 IP Port 234.523.213.462 321 21.236.432.123 66666 213.406.421.436 7324 需要帮助! 谢谢。对于此任务来说,正则表达式过于复杂 In [1]: "213.406.421.436:7324".split(":"
IP
234.523.213.462:321
21.236.432.123:66666
213.406.421.436:7324
我想
IP Port
234.523.213.462 321
21.236.432.123 66666
213.406.421.436 7324
需要帮助!
谢谢。对于此任务来说,正则表达式过于复杂
In [1]: "213.406.421.436:7324".split(":")
Out[1]: ['213.406.421.436', '7324']
In [2]: "213.406.421.436:7324".split(":")[0]
Out[2]: '213.406.421.436'
In [3]: "213.406.421.436:7324".split(":")[1]
Out[3]: '7324'
您可以从字符串中同时获取ip和端口,如下所示:
ip, port = "213.406.421.436:7324".split(":")
使用矢量化方法: 使用正则表达式的解决方案(如果只有数字,
:
和
):
使用
pd.Series.str.extract
simpleregex
df.IP.str.extract('(?P<IP>.+):(?P<Port>\d+)', expand=True)
IP Port
0 523.213.462 321
1 236.432.123 66666
2 406.421.436 7324
df.IP.str.extract('(?P<IP>\d{1,3}\.\d{1,3}\.\d{1,3}):(?P<Port>\d+)', expand=True)
IP Port
0 523.213.462 321
1 236.432.123 66666
2 406.421.436 7324
顺便说一下,端口号不能是
66666
,端口号是1-65535范围内的整数。
df.IP.str.extract('(?P<IP>.+):(?P<Port>\d+)', expand=True)
IP Port
0 523.213.462 321
1 236.432.123 66666
2 406.421.436 7324
df.IP.str.extract('(?P<IP>\d{1,3}\.\d{1,3}\.\d{1,3}):(?P<Port>\d+)', expand=True)
IP Port
0 523.213.462 321
1 236.432.123 66666
2 406.421.436 7324