Regular Expression in C# with Examples

CsharpProgrammingServer Side Programming

A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching.

Let’s see how to split a regular expression.

To split a string using regular expression, use the Regex.split.

Let’s say our string is −

string str = "Hello\r

Now use Regex.split to split the string as shown below −

string[] res = Regex.Split(str, "\r

The following is the complete code to split a string using Regular Expression in C# −


using System;
using System.Text.RegularExpressions;

class Demo {
   static void Main() {
      string str = "Hello\r
World";       string[] res = Regex.Split(str, "\r
");       foreach (string word in res) {          Console.WriteLine(word);       }    } }

Let us now see an example to remove extra whitespace.


using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   class Program {
      static void Main(string[] args) {
         string input = "Hello World ";
         string pattern = "\s+";
         string replacement = " ";

         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);
         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String: {0}", result);
Updated on 21-Jun-2020 15:52:20