【发布时间】:2015-06-12 23:14:53
【问题描述】:
我正在尝试使用 python 中的re 模块将字符串与正则表达式匹配。我想要得到的是来自 IP 地址的192.168.1.(所以缺少最后一个字节)。
我已经在正则表达式编辑器中试用了我的正则表达式,它似乎可以工作。变量original_ip 中已经包含192.168.1.65,所以我试图从中提取前3 个字节加上.。
我想做的是从192.168.1.5 获取那些192.168.1. 并让它返回一个字符串。
代码:
original_ip = subprocess.check_output("""ipconfig getifaddr en0""", shell=True)
print original_ip
#extract the xxx.xxx.xxx.number part from it. so the first 3 bytes
most_of_ip = re.match("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\b", original_ip).group(0)
print most_of_ip
错误代码:
Traceback (most recent call last):
File "arpdetector.py", line 120, in <module>
main()
File "arpdetector.py", line 99, in main
assign_new_address()
File "arpdetector.py", line 87, in assign_new_address
most_of_ip = re.match("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\b", original_ip).group(0)
AttributeError: 'NoneType' object has no attribute 'group'
【问题讨论】:
-
为什么不拆分加入呢?
-
如果您使用的是 Python 3.3 及更高版本,请使用
ipaddress库。 -
我正在使用 python 2.7 IIRC