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.
CodePudding user response:
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));
CodePudding user response:
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]
CodePudding user response:
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,3,4,5,6,7,8,9,10,11,12,13