Top C# Regex Code Examples

Regex class in C# represents regular expression. In this article, you’ll learn how to use C# Regex class to validate various user inputs.

Regex in C# defines a regular expression. C# Regex class offers methods and properties to parse a large text to find patterns of characters. In this article, you’ll learn how to use the .NET Regex class in C#.
 

Regular Expressions

 
A regular expression is used to check if a string matches a pattern or not. A regular expression or regex or regexp is a sequence of characters that defines a pattern. A pattern may consist of literals, numbers, characters, operators, or constructs. The pattern is used to search strings or files to see if matches are found. Regular expressions are often used in input validations, parsing, and finding strings. For example, checking a valid date of birth, social security number, full name where the first and the last names are separated by a comma, finding number of occurrences of a substring, replacing substrings, date formats, valid email formats, a currency format, and so on.
 

The Regex Class

 
In .NET, the Regex class represents the regular expression engine. It can be used to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection to generate a report.
 
The Regex class is defined in the System.Text.RegularExpressions namespace. The Regex class constructor takes a pattern string as a parameter with other optional parameters.
 
The following code snippet creates a Regex from a pattern. Here pattern is to match a word starting with char ‘M’.
  1. // Create a pattern for a word that starts with letter "M"  
  2. string pattern = @"\b[M]\w+";  
  3. // Create a Regex  
  4. Regex rg = new Regex(pattern);  
The following code snippet has a long text with author names that needs to be parsed.
  1. // Long string  
  2. string authors = "Mahesh Chand, Raj Kumar, Mike Gold, Allen O'Neill, Marshal Troll";  
The Matches method is used to find all the matches in a Regex and returns a MatchCollection.
  1. // Get all matches  
  2. MatchCollection matchedAuthors = rg.Matches(authors);  
The following code snippet loops through the matches collection.
  1. // Print all matched authors  
  2. for (int count = 0; count < matchedAuthors.Count; count++)  
  3. Console.WriteLine(matchedAuthors[count].Value);  
Here is the complete code:
  1. // Create a pattern for a word that starts with letter "M"  
  2. string pattern = @"\b[M]\w+";  
  3. // Create a Regex  
  4. Regex rg = new Regex(pattern);  
  5.   
  6. // Long string  
  7. string authors = "Mahesh Chand, Raj Kumar, Mike Gold, Allen O'Neill, Marshal Troll";  
  8. // Get all matches  
  9. MatchCollection matchedAuthors = rg.Matches(authors);  
  10. // Print all matched authors  
  11. for (int count = 0; count < matchedAuthors.Count; count++)  
  12. Console.WriteLine(matchedAuthors[count].Value);  
In the above example, the code looks for char ‘M’. But what if the word starts with ‘m’. The following code snippet uses RegexOptions.IgnoreCase parameter to make sure that Regex does not look for uppercase or lowercase.
  1. // Create a pattern for a word that starts with letter "M"  
  2. string pattern = @"\b[m]\w+";  
  3. // Create a Regex  
  4. Regex rg = new Regex(pattern, RegexOptions.IgnoreCase);  

Replacing multiple white spaces using Regex

 
The Regex.Replace() method is used to replace a matched string with a new string. The following example finds multiple whitespaces in a string and replaces with a single whitespace.
  1. // A long string with ton of white spaces  
  2. string badString = "Here is a strig with ton of white space." ;  
  3. string CleanedString = Regex.Replace(badString, "\\s+"" ");  
  4. Console.WriteLine($"Cleaned String: {CleanedString}");  
The following code snippet replaces whitespaces with a ‘-‘.
  1. string CleanedString = Regex.Replace(badString, "\\s+""-");  

Replacing multiple white spaces using Regex

 
The following example uses the regular expression pattern [a-z]+ and the Regex.Split() method to split a string on any uppercase or lowercase alphabetic character.
  1. // Spilt a string on alphabetic character  
  2. string azpattern = "[a-z]+";  
  3. string str = "Asd2323b0900c1234Def5678Ghi9012Jklm";  
  4. string[] result = Regex.Split(str, azpattern,  
  5. RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500));  
  6. for (int i = 0; i < result.Length; i++)  
  7. {  
  8.     Console.Write("'{0}'", result[i]);  
  9.     if (i < result.Length - 1)  
  10.         Console.Write(", ");  
  11. }  

Regular Expressions in C#

 
Regular expressions are a pattern matching standard for string parsing and replacement and is a way for a computer user to express how a computer program should look for a specified pattern in text and then what the program is to do when each pattern match is found. Sometimes it is abbreviated "regex". They are a powerful way to find and replace strings that take a defined format.
 
Here is a simple code example in C# that shows how to use regular expressions.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Text.RegularExpressions;  
  6.   
  7. namespace RegularExpression1  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             Regex r = new Regex(@"^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}");  
  14.             //class Regex Repesents an immutable regular expression.  
  15.   
  16.             string[] str = { "+91-9678967101""9678967101""+91-9678-967101""+91-96789-67101""+919678967101" };  
  17.             //Input strings for Match valid mobile number.  
  18.             foreach (string s in str)  
  19.             {  
  20.                 Console.WriteLine("{0} {1} a valid mobile number.", s,  
  21.                 r.IsMatch(s) ? "is" : "is not");  
  22.                 //The IsMatch method is used to validate a string or  
  23.                 //to ensure that a string conforms to a particular pattern.  
  24.             }  
  25.         }  
  26.     }  
  27. }  
Here is a detailed explaination of Regular Expressions and how to use them in C# and .NET:  
 

Regex for Email Validation

 
For validating multiple emails, we can use the following regular expressions. We are separating emails by using delimiter ';'
 
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;]{0,1}\s*)+$
 
If you want to use delimiter ',' then use this
 
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[,]{0,1}\s*)+$
 
and if you want to use both delimiter ',' and ';' then use this
 
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;,.]{0,1}\s*)+$
 
So by using above regular expression you can validate single email as well as multiple emails.
 
 

Validating User Input With Regular Expressions

 
This article explains how to use Regular expressions (the Regx class of the System.Text.RegularExpressions namespace) in C# and .NET.
 
We can use Regex.Match method that takes an input and regex and returns success if
  1. if (!Regex.Match(firstNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success) {}  
  2.     if (!Regex.Match(addressTextBox.Text, @"^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
  3.   
  4. if (!Regex.Match(cityTextBox.Text, @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
  5.      if (!Regex.Match(stateTextBox.Text, @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
  1. if (!Regex.Match(zipCodeTextBox.Text, @"^\d{5}$").Success)  
  2. {  
  3.     if (!Regex.Match(phoneTextBox.Text, @"^[1-9]\d{2}-[1-9]\d{2}-\d{4}$").Success)  
Learn more here:
 
 

Split String using Regex.split (Regular Expression) in C#

 
In this post, we will learn about how to split the string using Regex 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.     }  
  12. }  
The above code splits the string using \D+ and loops through check number and print.
 
Learn more here:
 
 

Replace Special Characters from string using Regex

 
In this blog I'll tell you about How to replace Special Characters Using Regex in C#.
 
If you are having a string with special characters and want's to remove/replace them then you can use regex for that.
 
Use this code:
  1. Regex.Replace(your String, @"[^0-9a-zA-Z]+""")  
This code will remove all of the special characters but if you doesn't want to remove some of the special character for e.g. comma "," and colon ":" then make changes like this:
  1. Regex.Replace(Your String, @"[^0-9a-zA-Z:,]+""")  
Similarly you can make changes according to your requirement.
 
Note:
 
Please note that regular expressions are not a solution of every tiny string parsing. If you need simple parsing that is provided by the String class or other classes, try to use those.
 

Further readings and References

 
If you’re new to regular expressions, I recommend reading this article Introduction to Regular Expressions.
 
Here is one more article: Regular Expressions Usage in C#