Page 1 of 1

Make this regex more efficient?

Posted: Thu Jun 30, 2005 12:45 pm
by pickle
Hi all,

I've successfully built a regular expression, but I'm quite the neophyte when it comes to these things. I was wondering if there was a more efficient pattern that could be employed here.

pattern: "/([0-9]{2,3}.{1}[0-9]{3}.{1}[0-9]{2,3}.{1}[0-9]{1,3}).*[0-9]+.*[0-9]+[^0-9]+([0-9]+)/"
target: "10.131.255.255 7625 0 11928"

I want to get the ip and the last number (in this case 11928).

I know that this pattern won't match ALL ips, but the ips I'm going to be dealing with are very regular, and will fit into this pattern.

Any ideas? Thanks.

Posted: Thu Jun 30, 2005 1:18 pm
by Chris Corbyn
The pattern is wrong anyway... didnt escape your dots :P

Code: Select all

/^(\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*? (\d+)$/
The IP makes it look long but it's needed unfortunately ;)

Posted: Thu Jun 30, 2005 1:30 pm
by pickle
That pattern you gave me returns empty matches. I had trouble with the \d not evaluating. Neither does \D or \s. Is there a php.ini thing I need to change to enable them?

I know I didn't escape the dots - it worked without me doing it. Using \. didn't match either - I had to use .{1} like I had.

It sounds like my system is very goofy when evaluating regular expressions.

Posted: Thu Jun 30, 2005 2:04 pm
by Chris Corbyn
Nothing in php.ini, regex are pretty standard. Just double check you're using it correctly. If it's still not working post some code and I'll have a look ;)

Code: Select all

$target = "10.131.255.255 7625 0 11928";
preg_match('/^(\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*? (\d+)$/', $target, $matches);
print_r($matches);

Code: Select all

Array
(
    ї0] => 10.131.255.255 7625 0 11928
    ї1] => 10.131.255.255
    ї2] => 11928
)
EDIT | If you define the pattern outside the preg_match() you need to double-up your backslashes :D

Posted: Fri Jul 01, 2005 1:31 am
by Syranide
As far as I know IPs can be of type 1.1.1.1 (no requirement on 2 digits in the first field).

I believe IBM or some other big shot companies have some IPs in the 9 first positions.

Posted: Fri Jul 01, 2005 2:47 am
by timvw

Code: Select all

$target = "10.131.255.255 7625 0 11928";
$matches = sscanf($target, "%d.%d.%d.%d %d %d %d");
print_r($matches);