Reputation: 1998
I have a string that contains numbers and other characters like: 123\n456? * ,, ;;; '' 333\n789/\\+-
and I'm trying to get only the numbers from it as array like
123
456
333
789
I've tried something like
serials = Regex.Replace(serials, @"\r\n?|\n|\t", " ");
var serialNumbers = Regex.Split(serials, @"(?<!($|[^\\])(\\\\)*?\\);");
but my array has something like
123 456? * ,,
empty
empty
'' 333 789/\\+-
Is there a way to split this string correctly?
Upvotes: 2
Views: 54
Reputation: 117
You can try something like:
int[] numbers = Regex.Split(input, @"\D+")
.Where(x => int.TryParse(x, out _))
.Select(int.Parse)
.ToArray();
if you want them like strings just remove the line with (int.Parse). The way it works it is the following: Splits the string by digits, then it tries to parse each string from the collection and if it's possible just put the string in the collection, (out _ is C# 7 features you can read more here -> Discards) and then if you need to you can parse each string to number and "materialize" them into array you can check here -> Enumerable.ToArray() method
Upvotes: 0
Reputation: 186833
Try matching, not splitting (i.e. extracting numbers from the string):
string[] numbers = Regex
.Matches(source, "[0-9]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
If you insist on splitting it can be
string[] numbers = Regex
.Split(source, "[^0-9]+");
which is more compact, but, probably, less readable.
Upvotes: 6