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.
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.
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));
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:
?: 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).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]+
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