No need for regular expressions here. Some background:
>>> import socket
>>> socket.inet_aton('255.255.255.255')
'xffxffxffxff'
>>> socket.inet_aton('255.255.255.256')
Traceback (most recent call last):
File "<input>", line 1, in <module>
error: illegal IP address string passed to inet_aton
>>> socket.inet_aton('my name is nobody')
Traceback (most recent call last):
File "<input>", line 1, in <module>
error: illegal IP address string passed to inet_aton
So:
import socket
def ip_address_is_valid(address):
try: socket.inet_aton(address)
except socket.error: return False
else: return True
Note that addresses like '127.1' could be acceptable on your machine (there are systems, including MS Windows and Linux, where missing octets are interpreted as zero, so '127.1' is equivalent to '127.0.0.1', and '10.1.4' is equivalent to '10.1.0.4'). Should you require that there are always 4 octets, change the last line from:
else: return True
into:
else: return address.count('.') == 3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…