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?
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.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With