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

148
Visualizações
Regex for a single range or comma separated string of numbers

I have a text field that I want to only accept a single range of numbers (eg. "1000-3000") OR a comma-separated list of numbers (eg. "1003", "1004", "2000") but not both. Some examples of expected results:

1000 (valid)
1000, 2000 (valid)
1000 ,2000 (valid)
1000, 2000, (valid)
,1000, 2000 (invalid)
1000,1000 (valid)
1000-2000, 3000-3500 (invalid).
1000-2000, 3000 (invalid).
1000 - 2000 (valid)
1000-2000 (valid)
,1000 (invalid)

This is what I have which doesn't work fully:

let input = "1000, 5000-6000"
input.match(/^(([0-9\s](,)?(-)?)*)+$/); // returns a match

input = "1000 - 3 000"  
input.match (/^(([0-9\s](,)?(-)?)*)+$/)// returns a match (space in second num)

let input = "5000-"
input.match(/^(([0-9\s](,)?(-)?)*)+$/); // returns a match

My version might fail in other ways I haven't found yet, but those 3 examples of matches shouldn't work. I'm using javascript/react.

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

0

You may use the following regex pattern, which matches a number either followed by a hyphen and another number (single range), or by comma and and another number, any number of times (CSV list).

^\d+(?:(?:\s*-\s*\d+)?|(?:\s*,\s*\d+)*\s*,?)$

Sample script:

var inputs = ["1000", "1000, 2000", "1000 ,2000", "1000, 2000,", "1000,1000", "1000 - 2000", "1000-2000", ",1000, 2000", "1000-2000, 3000-3500", "1000-2000, 3000", ",1000"];
inputs.forEach(x => console.log(x + " => " + /^\d+(?:(?:\s*-\s*\d+)?|(?:\s*,\s*\d+)*\s*,?)$/.test(x)));

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