C# regular expressions regex

C# provides a Regex class that can be used to work with regular expressions. Mostly I use it to search for a complex string pattern in another string or to replace occurrences of a sub-string within a string that matches the pattern.


-Search for a string pattern by using Regex.Match(string, pattern) method
+string contains a sub-string that matches the string pattern.
+pattern is the expression to be matched.

When writing a pattern the following special characters are useful:
\d: matches any digit character from 0 to 9.
\D: matches any character that is not a digit.
\s: matches any character that is a whitespace including tab, carriage return, form feed, new line, and vertical tab. \S: matches any character that is not a whitespace character.
\w: matches any character that is a character from a to z, A to Z, and underscore.
\W: matches any character that is a not a character from a to z, A to Z, 0 to 9, and underscore.
[...]: matches any character that is in  brackets.
[^...]: matches any character that is not in brackets.
.: matches any character that is not a new line.
?: matches the previous item 0 time or 1 time.
*: matches the previous item 0 time or more times.
+: matches the previous item 1 time or more times.
{n}: matches the previous item n times.
{n,}: matches the previous item more than n times.
{n,m}: matches the previous item from n to m times.
^: matches a pattern at the beginning of a string.
$: matches a pattern at the end of a string.

Example: To search for the first whitespace or the first group of whitespaces in the string "Regex provides power to programmers.", the pattern should be "\s+".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions ;
using System.Collections;

namespace Csharpproj
{

  
   class Program
   {
     static void Main(string[] args)
     {
        string string1= "Regex provides power to programmers.";
        string pattern= @"\s+";
        Match mat = Regex.Match(string1, pattern);
        if (mat.Success)
         Console.WriteLine("Found at position{0} ",mat.Index);
        else
         Console.WriteLine("No found");
    
        Console.Read();
     }
   }
}

To search for all whitespaces, use Matches(string,pattern) method instead of Match(string,pattern) method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions ;
using System.Collections;

namespace Csharpproj
{

  
   class Program
   {
     static void Main(string[] args)
     {
        string string1 = "Regex   provides     power to programmers.";
        string pattern= @"\s+";
        MatchCollection mat = Regex.Matches(string1, pattern);
        if (mat.Count>0 )
        {
           foreach(Match x in mat)
             Console.WriteLine("Found at position {0} ", x.Index);
        }
        else
           Console.WriteLine("No found");
    
        Console.Read();
     }
   }
}

If you want to show all matched values, use the Value property of the match object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions ;
using System.Collections;

namespace Csharpproj
{

  
   class Program
   {
     static void Main(string[] args)
     {
        string string1 = "My number is 9999. Your number is 89";
        string pattern= @"\d+";
        MatchCollection mat = Regex.Matches(string1, pattern);
        if (mat.Count>0 )
        {
           foreach(Match x in mat)
             Console.WriteLine("Found {0} at position {0} ",x.Value , x.Index);
        }
        else
           Console.WriteLine("No found");
    
        Console.Read();
     }
   }
}


-Replace occurrences of a sub-string by using Reg.Repalce(string,pattern,replacewith) method
Example: replace all groups of digits with hyphen

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions ;
using System.Collections;

namespace Csharpproj
{

  
   class Program
   {
     static void Main(string[] args)
     {
        string string1 = "My number is 9999. Your number is 89";
        string pattern= @"\d+";
        string strresult = Regex.Replace(string1, pattern, "-");
        Console.WriteLine(strresult);
    
        Console.Read();
     }
   }
}

You can match or replace different sub-strings by using | sign to separate the patterns.
The following example C# code replaces all groups of digits, whitespaces, and symbols in "My number is 9999. Your number is 89" string with hyphen.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions ;
using System.Collections;

namespace Csharpproj
{

  
   class Program
   {
     static void Main(string[] args)
     {
        string string1 = "My number is 9999. Your number is 89";
        string pattern= @"\d+|\s+|\W+";
        string strresult = Regex.Replace(string1, pattern, "-");
        Console.WriteLine(strresult);
    
        Console.Read();
     }
   }
}

Posted by: Dara | post date: 02-16-2013 | Subject: C# Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.