Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match an IP address [closed]

I am newbie with regex and I want to use preg_match function to find if a string is an IP address.

For example,

$string = "10.0.0.1"; preg_match($regex, $string); 

should return true. So, what $regex should be?

like image 857
ibrahim Avatar asked May 03 '11 06:05

ibrahim


People also ask

Which regex pattern can be used to find IP address?

Approach: Regex (Regular Expression) In C++ will be used to check the IP address. Specifying a range of characters or literals is one of the simplest criteria used in a regex.

How do I validate an IP address?

We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.

How do I grep an IP address?

In Linux you can use regular expressions with grep to extract an IP address from a file. The grep command has the -E (extended regex) option to allow it to interpret a pattern as a extended regular expression.

What is b regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.


1 Answers

Don't use a regex when you don't need to :)

$valid = filter_var($string, FILTER_VALIDATE_IP); 

Though if you really do want a regex...

$valid = preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $string); 

The regex however will only validate the format, the max for any octet is the max for an unsigned byte, or 255.

This is why IPv6 is necessary - an IPv4 address is only 32bits long and the internet is popular :)

like image 157
alex Avatar answered Oct 08 '22 23:10

alex