2

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?

Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186
Dana
  • 1,788
  • 3
  • 21
  • 51

2 Answers2

6

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.

Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186
0

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