1

I have created a RegEx expression (via some StackOverflow research) to match a list of IP addresses (both IPV4 and IPV6) separated with commas.

For example, the following would be acceptable

  • 192.168.1.1
  • 192.168.1.1,10.10.10.10
  • ::1,192.168.1.1
  • ::1

I have one problem with the expression which I have not been able to solve (this is perhaps the most complicated expression I have created). The expression currently allows for addresses to not be separated by a comma (due to how it allows an optional trailing comma).

((25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)(,\n|,?$))

Can anyone with more "RegEx Ninja Powers" help me to correct the above expression to allow a chain of IPV4 and/or IPV6 addresses separated with a comma with the trailing comma being optional (or indeed to not accept the trailing comma).

For reference, the regex is to be used in client-side validation on an MVC application.

In addition to helping me solve the above problem, I greatly appreciate any feedback on the RegEx itself, as that is the only way I will learn!

Update As this has now been marked as a "duplicate" I have edited the question to include an answer should anyone come across this in a search.

The following regex allows for the above requirements:

^((([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-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}))(,((([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-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4})))*$
melodiouscode
  • 2,105
  • 1
  • 20
  • 41
  • Do you need the separate capturing groups, or are you just trying to test to see whether there's a match or not? – CertainPerformance Oct 14 '18 at 08:03
  • As usual, `^{your_IP_pattern}(,{your_IP_pattern})*$` – Wiktor Stribiżew Oct 14 '18 at 08:04
  • @CertainPerformance Sorry I should have explained that, I am only interested in validating that the string contains the IP addresses in this style. Not in breaking them out. – melodiouscode Oct 14 '18 at 08:05
  • 1
    You can greatly simplify by repeating the first three `###.` groups with `{3}`: `(?:25[0-5]|2[0-4]\d|[01]?\d{1,2}\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:,\n|,?$)` – CertainPerformance Oct 14 '18 at 08:14
  • I had a cool idea to avoid repeating the long `1-255` test twice: use negative lookahead at the beginning of the string for any numbers greater than 255, and then you can just use `\d`s when matching for real: https://regex101.com/r/WKWREu/1 `^(?!.*(?:^|\.)(?:\d{4,}|0|[3-9]\d{2}|2[6-9]\d|25[6-9]))(?:\d+\.){3}\d+$` – CertainPerformance Oct 16 '18 at 01:05

0 Answers0