CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [esludds] Reg ex script: Edit Log



Kenosis
User

Dec 4, 2013, 11:15 AM


Views: 2151
Re: [esludds] Reg ex script

Your IP-matching regex needs a little attention. For example:

Code
use warnings; 
use strict;

while (<DATA>) {
if (m/\d{1,2}.\d{1,3}.\d{1,3}.\d{1,3}/) {
print "Yes: $_";
}
else {
print "No : $_";
}
}

__DATA__
127.0.0.1
9995.333.777.000
255.255.255.0
abc.def.ghi.jkl
10_376_14.0
1234567890


Output:

Code
Yes: 127.0.0.1 
Yes: 9995.333.777.000
Yes: 255.255.255.0
No : abc.def.ghi.jkl
Yes: 10_376_14.0
Yes: 1234567890


Note that it's matching too much. Also, the leading m is used only when ^ (match from the beginning) or $ (denoting the end) is used in the regex, so that can be removed:


Code
/\d{1,2}.\d{1,3}.\d{1,3}.\d{1,3}/


Didn't you mean /\d{1,2} for the first octet, like all the rest? Also, the period in your regex isn't escaped \., so it will match any character except a newline. Making these changes, you get:

Code
/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/

with an output used in the script above of:

Code
Yes: 127.0.0.1 
Yes: 9995.333.777.000
Yes: 255.255.255.0
No : abc.def.ghi.jkl
No : 10_376_14.0
No : 1234567890

This is better, but you don't want 9995.333.777.000. You want to match an IP that's surrounded by a word boundary, and that's represented by \b. So, we now have:

Code
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/

with an output of:

Code
Yes: 127.0.0.1 
No : 9995.333.777.000
Yes: 255.255.255.0
No : abc.def.ghi.jkl
No : 10_376_14.0
No : 1234567890

This is matching only what we want matched.

Now, you can go one step further here, using the notation in \d{1,3}. Notice that the IP addresses have a repeating pattern: (nnn.) x 3 (assuming three digits in the octets), following by nnn as the last octet. You can represent that in a regex as follows:

Code
/\b(?:\d{1,3}\.){3}\d{1,3}\b/

And this generates the same output as the last regex, but it's just a bit shorter.

Hope this helps!


(This post was edited by Kenosis on Dec 4, 2013, 11:17 AM)


Edit Log:
Post edited by Kenosis (User) on Dec 4, 2013, 11:17 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives