user7353226
user7353226

Reputation: 55

regex for multiple IPs comma separated with or without subnet

I have regex for IPv4 address:

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$

and i have regex for IPv4 CIDR range :

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(/([0-9]|[1-2][0-9]|3[0-2]))$

the issue is how should i repeat it using comma separated

pattern:

XXX.XXX.XXX.XXX, XXX.XXX.XXX.XXX/XX, XX.XX.XX.XX, XX.XX.XX.XX/X , XX.XX.XX.X test data--

123.123.13.11, 1.0.0.0, 1.0.0.1/3, 1.0.0.0/20

am using http://regexr.com/ to build by regex, the regex which i build is below and not working--

/(((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))),?)/g

Upvotes: 0

Views: 3526

Answers (2)

Tezra
Tezra

Reputation: 8833

To loop surround regex with ()* ex (<regex>)* if matching start and end then move terminators out of loop like ^(regex)*$

To match , or end-of-line append ([,\s]+|$) exclude \s if you don't want whitespace, + means match one or more.

This should work for you to match the whole string. Remove * at end for valid parts; surround with ^ $ to match full string.

IPV4 = (([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])
Optional subnet = (\/([4-9]|[12][0-9]|3[0-2]))?
coma or end of line = (,|$)
Putting it together = (((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([4-9]|[12][0-9]|3[0-2]))?)([,\s]+|$))*

Or, for minimal group matching ((?!\\/) is negative look ahead for /, not all regex engines support negative look ahead)

(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]?)(\/(3[0-1]|2[0-9]|1[0-9]|[4-9]))?(?!\/)\b

Upvotes: 1

juanferrer
juanferrer

Reputation: 1250

Is this what you're looking for?

/((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]?)(\/(3[0-1]|2[0-9]|1[0-9]|[4-9]))\,?\b){1,}/g

Edit: Breakdown

Match an 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]?)

(\/(30|2[0-9]|1[0-9]|[4-9]))? / followed by a number between 4 and 31.

\,? Comma. Optional.

? Space. Optional.

\b End of word.

){1,} End of capturing group. All at least once.

Upvotes: 1

Related Questions