1

I'm trying to get a working regex syntax to match the following values. The field is able to contain either

  1. Comma-separated values or a single value. Such as "22" or "22,456"
  2. A range of ports with a dash. Such as "22-600"

With values possible from 1 to 65535

Attempts

Matches a single port correctly, however doesn't support a "," or "-"

^(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{1,3}|[0-9])(?:,(?1))*$

Doesn't match a single port but does match multiple comma seperated ports

^(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{1,3}|[0-9])(?:,(?1))(?:,(?1))*$

Doesn't match a single port but does match a port range

^(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{1,3}|[0-9])(?:-(?1))(?:(?1))*$
2
  • Can you use a PowerShell function instead of simply a very complicated regex?
    – Glenn
    Oct 7, 2020 at 4:41
  • I can, But I'm trying to use a JSON Schema to validate the JSON files that come through. That's what management wants to happen so it's more of a "proper" test instead of some custom PowerShell function Oct 7, 2020 at 5:21

1 Answer 1

1

I suggest:

^(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3})-(?1)|(?1)(,(?1))+$

Your first regex hat [0-9] as last option, which allows 0 as value. I changed that and added the other options.

See https://regexr.com/5dvdk

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .