In this tutorial we will see how to extract numbers from a string using Regex.split in C # programming language, Regex.split handles a specified delimiter as a pattern.
To use, Regex add the namespace below.
1 2 3 | using System.Text.RegularExpressions; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; using System.Text.RegularExpressions; public class Program { public static void Main() { string str = "5 dogs, 3 horses, 40 cats and 2 birds."; string[] numbers = Regex.Split(str, @"\D+"); foreach (string nbr in numbers) { int number; if (int.TryParse(nbr, out number)) { Console.WriteLine(nbr); } } } } |