I write Perl one liner code in order to match IP address according to the following rule:
match only the three first octets while the four octet must be valid 0-255 , additional to that number or " . " must not be exists before the first octet and number or " . " must not be exist also after the four octet
example
export IP=100.187.34
example of IP's that should matched
:100.187.34.12:.10
IP=100.187.34.100$
AAA100.187.34.199BBB
address:100.187.34.210+
example of IP's that shouldn't matched
55.100.187.34.99
.100.187.34..
100.187.34.100.1
100.187.34.2100
1.100.187.34
100.187.34.1.1
so this is my code (not work according to my rules):
echo [...]xxx.xxx.xxx.xxx[...] | perl -pe 'print if /(?<![\d.])\Q$ENV{IP}\E(?=\.(?:1?\d?\d|2[0-4][0-9]|25[0-5])(?!\d))/; '
the problem is my code matched almost any number
please advice what I need to fix in my code in order to match the IP's only according to the rules
Here are some examples of IP regexp matching from O'Reilly's Regular Expressions Cookbook:
Simple regex to check for an IP address:
^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$
Accurate regex to check for an IP address:
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}↵
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Simple regex to extract IP addresses from longer text:
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b
Accurate regex to extract IP addresses from longer text:
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}↵
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
Simple regex that captures the four parts of the IP address:
^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$
Accurate regex that captures the four parts of the IP address:
^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.↵
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.↵
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.↵
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
perl -e '$v=quotemeta($ENV{IP});print if /$v\.(?:1?\d?\d|2[0-4][0-9]|25[0-5])(?!\d)/?1:0'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.