1

Is this a valid regular expression for IP-addresses?

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5]{2}|0{2}|0{3})\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-5]{2}|0{2}|0{3})$
Cylian
  • 10,970
  • 4
  • 42
  • 55
Tahir khan
  • 13
  • 1
  • 4
  • Please share a bit more information: what do you want to achieve with the regex? Must it extract certain blocks? Should it simply validate? Must it validate only a certain range? Also consider sharing a few example IP-adresses where you want to let the regex loose on. – berkes Jan 07 '13 at 11:43
  • 1
    http://www.regular-expressions.info/examples.html – Grijesh Chauhan Jan 07 '13 at 11:44
  • Hi May be this solution on Stackoverflow can help you. http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address – Sigar Dave Jan 07 '13 at 11:44
  • Hi May be this solution on Stackoverflow can help you. http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address – Sigar Dave Jan 07 '13 at 11:45

2 Answers2

4

Not correct : in the first part ((....){3}) : the last 2[0-5]{2} will allow 201, 254, etc, but not 239, etc (ie, last digit >5)

Now, a 5 seconds search in a search engine gave me this url : http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/

And as @Sigardave pointed out, a more "local" solution ^^ (ie, in the same area of the Internet) : Regular expression to match DNS hostname or IP Address?

Community
  • 1
  • 1
Olivier Dulac
  • 3,695
  • 16
  • 31
2

This is how IPAddr in standard lib does it:

# Returns +true+ if +addr+ is a valid IPv4 address.
def valid_v4?(addr)
  if /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\Z/ =~ addr
    return $~.captures.all? {|i| i.to_i < 256}
  end
  return false
end
steenslag
  • 79,051
  • 16
  • 138
  • 171