Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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:

  • ^ Start of string
  • (?:TCP|UDP) Match one of the alternatives
  • \/\d+(?:-\d+)? Match / 1+ digits and optionally - and 1+ digits
  • (?: Non capture group to repeat as a whole part
    • ,(?:TCP|UDP)\/\d+(?:-\d+)? Match a , and repeat the same pattern
  • )* Close non capture group and optionally repeat (If there should be at least 1 comma, change the * to +)
  • $ End of string

Regex demo

about 4 years ago · Juan Pablo Isaza Relatório

0

Alternative: split up the string, use Array.filter and a relative simple RegExp for testing.

const valid = `TCP/53,UDP/53,TCP/10-20,UDP/20-30`;
const invalid = `TCP/53UDP53,TCP/10-20UDP20-30`;

console.log(`${valid} ok? ${checkInp(valid)}`);
console.log(`${invalid} ok? ${checkInp(invalid)}`);

function checkInp(str) {
  return str.split(`,`)
    .filter(v => /^(TCP|UDP)\/\d+(?:-\d+)*$/.test(v))
    .join(`,`)
    .length === str.length;
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda