Regex.Split, digits. Regex.Split can extract numbers from strings. We get all the numbers that are found in a string. Ideal here is the Regex.Split method with a delimiter code.
Method notes. We describe an effective way to get all positive ints. For floating point numbers, or negative numbers, another solution will be needed.
Input and output. Let us first consider the input and output of our Regex.Split call. We want to extract digit sequences of 1 or more chars. This leaves us with numbers (in a string array).
Example program. The const input string has 4 numbers in it: they are one or two digits long. To acquire the numbers, we use the format string "\D+" in the Regex.Split method.
using System;
using System.Text.RegularExpressions;
const string input = "ABC 4: 3XYZ 10";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}Number: 4
Number: 3
Number: 10\D Non-digit char.
+ 1 or more of char.
Notes, pattern. For handling numbers in regular expressions, the "\d" and "\D" codes are important. The lowercase "d" means digit character. The uppercase means non-digit char.
Summary. We extracted integers inside a string. And we converted the results to ints. The Regex.Split method is useful for this purpose. It allows flexible, complex delimiters.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 10, 2024 (simplify).