Split String Using Regex.split (Regular Expression) In C#

In this post, we will learn how to split the string using RegEx in C#. Regex splits the string based on a pattern. It handles a delimiter specified as a pattern. This is why Regex is better than string.Split. Here are some examples of how to split a string using Regex in C#. Let's start coding.

For use, Regex adds the below namespaces for spliting a string.

  1. using System;  
  2. using System.Text.RegularExpressions;  
  3. using System.Collections.Generic; 
Example 1

Split digits from a string using Regex.
  1. string Text = "1 One, 2 Two, 3 Three is good.";  
  2.   
  3. string[] digits = Regex.Split(Text, @"\D+");  
  4.   
  5. foreach (string value in digits)  
  6. {  
  7.     int number;  
  8.     if (int.TryParse(value, out number))  
  9.     {  
  10.         Console.WriteLine(value);  
  11.     }  

 The above code splits the string using \D+ and loops through check number and print.
 
C#
 
Example 2

Split operation from a string using Regex.
  1. string operation = "315 / 1555 = 0";  
  2.   
  3. string[] operands = Regex.Split(operation, @"\s+");  
  4.   
  5. foreach (string operand in operands)  
  6. {  
  7.     Console.WriteLine(operand);  

 The above code splits the string using \s+ and loops through print.

C#
 
Example 3

Split the string from where there is a capital word in the string, using Regex.
  1. string sentence = "Hello This Is testing application for Split STring";  
  2.   
  3. string[] uppercaseWords = Regex.Split(sentence, @"\W");  
  4.   
  5. var list = new List();  
  6. foreach (string value in uppercaseWords)  
  7. {  
  8.     if (!string.IsNullOrEmpty(value) &&  
  9.         char.IsUpper(value[0]))  
  10.     {  
  11.         list.Add(value);  
  12.     }  
  13. }  
  14.   
  15. foreach (var value in list)  
  16. {  
  17.     Console.WriteLine(value);  

The above code splits "sentence" using "\W" and splits the string that contains the capital letters in word and stores on the list. After completing the first loop, the second loop displays all words that contain the uppercase letters in the word.
 
C# 

Example 4

Split URL or Path using/char from a string.
  1. string URL = "C:/TestApplication/1";  
  2.   
  3. string[] splitString = Regex.Split(URL, @"/");  
  4.   
  5. foreach (var item in splitString)  
  6. {  
  7.     Console.WriteLine(item);  

The above code splits string "/" and loop through print on the screen.
 
C# 
Next Recommended Reading Split String Without Using Split Method