javascriptregexportnetwork-service

Regex for network service port definitions


my collegue and I try to build a Regex (Javascript) to validate an input field for a specific format. The field should be a comma seperated list of port declarations and could look like this:

TCP/53,UDP/53,TCP/10-20,UDP/20-30

We tried this regex:

/^[TCP/\d+,|UDP/\d+,|TCP/\d+\-\d+,|UDP/\d+\-\d+,]*[TCP/\d+|UDP/\d+|TCP/\d+\-\d+|UDP/\d+\-\d+]$/g

the regex matches, but also matches other strings as well, like this one:

TCP/53UDP53,TCP/10-20UDP20-30

Thanks for any guidance!


Solution

  • You don't need all those alternations, and the [ ] are not used for grouping like that. You can also make the - and digits part optional using grouping (?:...)?

    To match that string format:

    ^(?:TCP|UDP)\/\d+(?:-\d+)?(?:,(?:TCP|UDP)\/\d+(?:-\d+)?)*$
    

    The pattern matches:

    Regex demo