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;
Example 1
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);
- }
- }
The above code splits the string using \D+ and loops through check number and print.
Example 2
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);
- }
The above code splits the string using \s+ and loops through print.
Example 3
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);
- }
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.
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);
- }
The above code splits string "/" and loop through print on the screen.