Mark
Mark

Reputation: 2148

Can I optimize this perl regex

I am trying to match some ip names (dotted decimal or names). I need to match any of the following:

hostname-1-2-3
hostname-1-2-3.here.somewhere.com
hostname-1-2-3.here or
192.168.1.2
hostname-1-2.*

I have this if statement:

if ($name !~ m/^[a-zA-Z0-9-\.]+$/ and 
    not $name =~ m/^[a-zA-Z0-9-]\.\*/ and 
    not $name =~ m/^[0-0]+\.[0-9]+\.[0-9]+\.[0-9]+$/)
{
    print "inside if\n";
}
else {
    print "inside else\n";
}

It now prints 'inside else' for the first 4 names, and 'inside if' for the last name (that name would be expanded in the code to several host names.

This is the behavior I want, I am just wondering if my regex could be combined since the first two matches are very similar.

Upvotes: 0

Views: 67

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

You're doing too many negations here... It's not easy to read like that.

Here's a solution for you:

^(?:
    (?:\d+\.){3}\d+
    |
    [a-zA-Z][-a-zA-Z0-9.]*
)$

Demo

This regex will match:

  • IP addresses of the form ##.##.##.## (4 numbers, no less, no more)
  • An address (letters, digits, dashes and dots) starting with a letter

I think that this should satisfy the same requirements.

Upvotes: 1

Related Questions