Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!