Tahir khan
Tahir khan

Reputation: 13

Is it a valid Regular expression for IP address

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})$

Upvotes: 1

Views: 5880

Answers (2)

steenslag
steenslag

Reputation: 80065

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

Upvotes: 2

Olivier Dulac
Olivier Dulac

Reputation: 3791

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?

Upvotes: 4

Related Questions