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

289
Visualizações
How to select all the numbers from a comma separated and spaces string?

How to select all the numbers from the below string?

str = "1,2, 4,5 ,6 7 8 9 10, 11, 13"

I tried using split(',') but it doesn't work for spaces.

As it contains spaces as well.

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

0

Just make a regular expression and match on numbers

console.log("1,2, 4,5 ,6 7 8  9 10, 11, 13".match(/\d+/g).map(Number));

about 4 years ago · Juan Pablo Isaza Relatório

0

split can take a regular expression. So you can give it a regular expression that robustly defines your delimiting syntax. (...which may be similar but slightly different for others reading this question, which is why I'm providing this answer.)

I suspect you'll actually want to permit at most 1 comma, with optional whitespace before and after, or 1 or more spaces. But for example, I suspect that you won't two or more commas to be interpreted as a single delimiter, but rather more likely an error in the input text. For example it may be desirable to interpret 1,,2 as [1, 0, 2]. (After all, in JavaScript, Number("") is 0). It depends entirely on the syntax you choose for yourself.

Such a regular expression could be:

(?:\s*,\s*)|\s+

There's a lot going on here:

  • when you split with a regex, captured groups are kept in the output so you have to use a ?: non-capturing group.
  • \s*,\s* has to appear before \s+ in the alternation (|) construction because it needs to be matched greedily to form the longer delimiter (to include the comma in the delimiter if there is one, and not just the space before it).
  • This should work with numbers like 3.14, -1, 1.21e9, 0x42, Infinity etc.

console.log("1,2, 4,5 ,6 7 8  9 10, 11, 13".split(/(?:\s*,\s*)|\s+/).map(Number));

If you do want ,, to be a single delimiter, the regex could just be [,\s]+

about 4 years ago · Juan Pablo Isaza Relatório

0

Without using regular expressions:

string str = "1,2, 4,5 ,6 7 8  9 10, 11, 13";
List<string> list = str.Replace(" ", ",").Split(',').ToList();
list.RemoveAll(x => x == string.Empty);

List contains: 1,2,4,5,6,7,8,9,10,11,13

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