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.
- using System;
- using System.Text.RegularExpressions;
- using System.Collections.Generic;
Split digits from a string using Regex.
- string Text = "1 One, 2 Two, 3 Three is good.";
- string[] digits = Regex.Split(Text, @"\D+");
- foreach (string value in digits)
- {
- int number;
- if (int.TryParse(value, out number))
- {
- Console.WriteLine(value);
- }
- }

Split operation from a string using Regex.
- string operation = "315 / 1555 = 0";
- string[] operands = Regex.Split(operation, @"\s+");
- foreach (string operand in operands)
- {
- Console.WriteLine(operand);
- }

Split the string from where there is a capital word in the string, using Regex.
- string sentence = "Hello This Is testing application for Split STring";
- string[] uppercaseWords = Regex.Split(sentence, @"\W");
- var list = new List();
- foreach (string value in uppercaseWords)
- {
- if (!string.IsNullOrEmpty(value) &&
- char.IsUpper(value[0]))
- {
- list.Add(value);
- }
- }
- foreach (var value in list)
- {
- Console.WriteLine(value);
- }
Example 4
Split URL or Path using/char from a string.
- string URL = "C:/TestApplication/1";
- string[] splitString = Regex.Split(URL, @"/");
- foreach (var item in splitString)
- {
- Console.WriteLine(item);
- }

Dante SantosPosted Nov 1, 2019, 8:10 AM
Hi all! Like in Regex.Split(sentence, @"\W"), how would be the line for names that has "-" like in "McMann-Stringer"? I can't split that name. Thank you!!
Viknaraj ManogararajahPosted Jul 21, 2018, 10:42 PM
Nice Article, Thank you for sharing