Question

I have a regex that will match IP addresses.

it looks like:

^(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]?|*|25[0-5]-25[0-5]|2[0-4][0-9]-25[0-5]|2[0-4][0-9]-2[0-4][0-9]|[01]?[0-9][0-9]?-25[0-5]|[01]?[0-9][0-9]?-2[0-4][0-9]|[01]?[0-9][0-9]?-[01]?[0-9][0-9])$

which you will mostly recognise from many other posts here on SO. however I have modded it to match the range form XXX.XXX.XXX.XXX-XXY

However it now seems a little complex, particularly the final () capture. I would like some help to simplify this regex if possible.

Just to be clear

aaaa - not matched
999.1.1.1 - not matched
1.1.1.999 - not matched
192.168.2.1 - matched
192.168.2.* - matched
192.168.2.10-20 - matched

EDIT

I forgot to mention that I need the existing capture groups as well.

Was it helpful?

Solution

You could perhaps use optional groups (?: ... )? instead and use another grouping for the first 3 parts of the IP?

^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
 (?:25[0-5](?:-25[0-5])?|
  2[0-4][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]?))?|
  \*)$

regex101 demo


Updated with capture groups

^((?: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](?:-25[0-5])?|
  2[0-4][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]?))?|
  \*)$

OTHER TIPS

This works -

^(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]?)(?:\-(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(\*))$

As can be seen here

This should work and is a bit shorter:

^((25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}(\*|(25[0-5]|2[0-4]\d|[01]?\d{1,2}))(\-(25[0-5]|2[0-4]\d|[01]?\d{1,2}))?$

See: http://regex101.com/r/sD9iZ0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top