Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

284
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda