There is a simpler way. You just need to split the string on .
and check that every number is between 0 and 255.
Additionally, you can check for hexa and split on :
for IPv6.
Just because I think it’s funny:
^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$
Here is a regex that should handle IPs (v4).