TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Regex.Split Numbers

This C# example program uses Regex.Split to get numbers from a string.

Regex.Split numbers. Regex.Split can extract numbers from strings.

We get all the numbers that are found in a string. Ideal for this purpose is the Regex.Split method with a delimiter code. We describe an effective way to get all positive ints.

Regex.Split

Example. Please notice how the System.Text.RegularExpressions namespace is included. The const input string has four 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.

Note: This indicates that we want to use any number of one or more non-digit characters as a delimiter.

C# 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

The Regex.Split method will return the numbers in string form. The result array may also contain empty strings. To avoid parsing errors, we use the string.IsNullOrEmpty method. Finally, we invoke the int.Parse method to get integers.

IsNullOrEmptyParse

Summary. In this demonstration, we extracted four integers that were embedded in a string literal, and then converted them to integers. The Regex.Split method is useful for this purpose. It allows flexible, complex delimiters.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf