C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pattern: The pattern "\D+" indicates that we want to use any number of one or more non-digit characters as a delimiter.
Using: Please notice how the System.Text.RegularExpressions namespace is included.
RegexReturn: The Regex.Split method will return the numbers in string form. The result array may also contain empty strings.
Info: To avoid parsing errors, we use the string.IsNullOrEmpty method. Finally, we invoke the int.Parse method to get integers.
IsNullOrEmpty, IsNullOrWhiteSpaceint.ParseC# program that uses Regex.Split on string
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
const string input = "There are 4 numbers in this string: 40, 30, and 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);
}
}
}
}
Output
Number: 4
Number: 40
Number: 30
Number: 10
Pattern:
\D Non-digit char.
+ 1 or more of char.