Regular expressions, commonly known as regex, are powerful and flexible tools used for pattern matching and manipulation of text. They are essentially a sequence of characters that define a search pattern.
Regular expressions are used to perform various operations on strings, such as searching for specific patterns, validating input, or transforming text data. They are widely supported in programming languages, text editors, and command-line tools.
A regular expression consists of two types of characters: literal characters and metacharacters. Literal characters represent themselves and match the same characters in the text being searched. For example, the regular expression "cat" matches the string "cat" exactly.
Metacharacters, on the other hand, have special meanings and are used to define the rules and patterns within the regular expression. Some common metacharacters include:
- Dot (.) - Matches any single character except a new line.
- Asterisk (*) - Matches zero or more occurrences of the preceding character or group.
- Plus sign (+) - Matches one or more occurrences of the preceding character or group.
- Question mark (?) - Matches zero or one occurrence of the preceding character or group.
- Square brackets ([])- Defines a character class and matches any single character within the brackets.
- Caret (^) - Matches the beginning of a line or string.
- Dollar sign ($) - Matches the end of a line or string.
- Pipe (|) - Represents the OR operator, allowing for multiple alternatives.
Regular expressions can be as simple as matching a specific word or character, or they can be more complex and involve combinations of metacharacters to define intricate patterns.
Here are a few examples of what you can do with regular expressions:
- Search for email addresses within a document: \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}\b
- Validate a phone number in a specific format:
- ?
- \d
- 3
- ?\d3?[-.\s]?\d{3}[-.\s]?\d{4}
- Find and replace all occurrences of a word: s/old_word/new_word/g
- Extract all URLs from a webpage: https?://[\w./?-]+
Regular expressions provide a concise and powerful way to work with text data, and learning how to use them effectively can greatly enhance your ability to manipulate and process strings in various contexts.
In C#, regular expressions are supported through the System.Text.RegularExpressions namespace, which provides classes and methods for working with regular expressions. Here's an overview of how you can use regular expressions in C#:
Creating a regular expression object
You can create a Regex object by instantiating it with a pattern string as the constructor argument. For example:
Regex regex = new Regex(@"\b\w+"); // Matches one or more word characters
Matching patterns
The Regex object provides methods for matching patterns in strings. The Match method returns the first occurrence of the pattern in the input string, and the Matches method returns all occurrences as a collection of Match objects. For example:
string input = "Hello, world!";
Match match = regex.Match(input);
if (match.Success)
{
string matchedText = match.Value; // "Hello"
int startIndex = match.Index; // 0
int length = match.Length; // 5
}
Checking for matches
The Regex object has an IsMatch method that checks if a pattern matches a given string. It returns a boolean indicating whether there was a match. For example:
bool isMatch = regex.IsMatch(input);
if (isMatch)
{
// There is a match
}
Finding and replacing patterns
The Regex class provides a Replace method that allows you to find and replace patterns in a string. You can specify the replacement string and optional options to modify the behavior. For example:
string replacedText = regex.Replace(input, "Hi");
// replacedText will be "Hi, world!"
These are just some of the basic operations you can perform with regular expressions in C#. The Regex class offers many more methods and options for working with patterns, such as specifying options like case-insensitivity or multiline matching, capturing groups, and more.
Remember to escape special characters in the pattern string using a backslash (\) if you want to match those characters literally.
Regular expressions in C# provide a powerful and flexible way to work with text data, allowing you to search, validate, and transform strings efficiently.
Detailed Regex Example
Let's create a complete application with a few patterns.
Pattern #1:
Regex objNotNaturalPattern=new Regex("[^0-9]");
Pattern #2:
Regex objNaturalPattern=new Regex("0*[1-9][0-9]*");
Pattern #1 will match strings other than 0 to 9.
- The ^ symbol is used to specify, not condition.
- the [] brackets if we are to give range values such as 0 - 9 or a-z or A-Z
In the above example, input 'abc' will return true, and '123' will return false.
Pattern #2 will match strings that are natural numbers. Natural numbers are numbers that are always greater than 0. Pattern 0* says a natural number can be prefixed with zeros or non-zero. The next [1-9] says it should contain at least one number from 1 to 9 followed by any numbers of 0-9's.
In this case, input '0007' will return true, and '00' will return false.
Basic operators to understand in Regex:
- "*" matches 0 or more patterns
- "?" matches a single character
- "^" for ignoring matches.
- "[]" for searching range patterns.
The complete source code example provides functions to check IsNaturalNumber, IsWholeNumber, IsPositiveNumber, IsInteger, IsNumber, IsAlpha, and IsAlphaNumeric.
// Source Code starts
using System.Text.RegularExpressions;
using System;
/*
<HowToCompile>
csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs
</HowToComplie>
*/
class Validation
{
public static void Main()
{
String strToTest;
Validation objValidate = new Validation();
Console.Write("Enter a String to Test for Alphabets:");
strToTest = Console.ReadLine();
if (objValidate.IsAlpha(strToTest))
{
Console.WriteLine("{0} is Valid Alpha String", strToTest);
}
else
{
Console.WriteLine("{0} is not a Valid Alpha String", strToTest);
}
}
// Function to test for Positive Integers.
public bool IsNaturalNumber(String strNumber)
{
Regex objNotNaturalPattern = new Regex("[^0-9]");
Regex objNaturalPattern = new Regex("0*[1-9][0-9]*");
return !objNotNaturalPattern.IsMatch(strNumber) &&
objNaturalPattern.IsMatch(strNumber);
}
// Function to test for Positive Integers with zero inclusive
public bool IsWholeNumber(String strNumber)
{
Regex objNotWholePattern = new Regex("[^0-9]");
return !objNotWholePattern.IsMatch(strNumber);
}
// Function to Test for Integers both Positive & Negative
public bool IsInteger(String strNumber)
{
Regex objNotIntPattern = new Regex("[^0-9-]");
Regex objIntPattern = new Regex("^-[0-9]+$|^[0-9]+$");
return !objNotIntPattern.IsMatch(strNumber) && objIntPattern.IsMatch(strNumber);
}
// Function to Test for Positive Number both Integer & Real
public bool IsPositiveNumber(String strNumber)
{
Regex objNotPositivePattern = new Regex("[^0-9.]");
Regex objPositivePattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber);
}
// Function to test whether the string is valid number or not
public bool IsNumber(String strNumber)
{
Regex objNotNumberPattern = new Regex("[^0-9.-]");
Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
return !objNotNumberPattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
}
// Function To test for Alphabets.
public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern = new Regex("[^a-zA-Z]");
return !objAlphaPattern.IsMatch(strToCheck);
}
// Function to Check for AlphaNumeric.
public bool IsAlphaNumeric(String strToCheck)
{
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
return !objAlphaNumericPattern.IsMatch(strToCheck);
}
}
// Source Code End
Here are some of the most common Regex code examples in C#:

Dharmendra Kumar PanditPosted Jan 4, 2021, 9:02 AM
NIce article..........
Dhaval ParikhPosted Jul 23, 2020, 3:53 AM
I have an expression like this Regex.Replace(str, @"[^0-9\.]+", ""); , My understanding is it replace any other character in str other than 0 to 9 and . with an "", what is the extra + for?
Rikam PalkarPosted Jun 3, 2020, 1:15 AM
It is a good read.
Logesh PalaniPosted Jul 5, 2019, 9:55 AM
Nice article :)
Abhishek MishraPosted Oct 5, 2018, 4:04 AM
Very good info
Aswini SridharPosted Dec 20, 2017, 6:06 AM
Hmm.. Nice one... :)
Ramesh PalaniappanPosted Aug 18, 2016, 8:14 AM
Good One
kalu singh raoPosted Jul 7, 2016, 8:38 AM
Nice...
Dileep SharmaPosted May 7, 2016, 4:04 AM
Nice Article, thank you so much
Bhuvanesh MohankumarPosted Apr 19, 2016, 2:31 PM
Good one
Bhuvanesh MohankumarPosted Apr 19, 2016, 8:16 AM
Easy to understand, good one
MannanPosted Apr 8, 2016, 12:58 AM
nice share
Prashant VermaPosted Mar 10, 2016, 3:17 AM
Good one
Prashant VermaPosted Mar 10, 2016, 3:16 AM
nice Article
Prashant VermaPosted Mar 10, 2016, 3:14 AM
Nice
Sonu ChaudharyPosted Feb 25, 2016, 6:29 AM
keep sharing
Sonu ChaudharyPosted Feb 25, 2016, 6:28 AM
nice article
Aswini SridharPosted Feb 17, 2016, 11:58 PM
Good one!
Shailesh UkePosted Feb 16, 2016, 1:53 AM
Nice Article
Sr KarthigaPosted Feb 10, 2016, 9:15 AM
Good one sir its very intresting
Irfan AcPosted Jan 25, 2016, 1:16 AM
keep sharing
Ashish SrivastavaPosted Jan 14, 2016, 5:39 AM
nice
Arul RPosted Jan 4, 2016, 10:37 PM
Nice share
Chandu KumawatPosted Oct 14, 2015, 10:15 AM
nice
Yashwanth MuthineniPosted Aug 27, 2015, 7:04 AM
Nice
SharadPosted Jul 17, 2015, 3:38 AM
good one..
Govinda Rajulu YemineniPosted Jul 14, 2015, 5:09 AM
Nice one
Merajuddin AnsariPosted Jul 12, 2015, 8:11 AM
Good one
Upendra Pratap ShahiPosted May 22, 2015, 6:26 AM
nice
Md. Raskinur RashidPosted Jan 10, 2015, 12:16 PM
very much understandable...
Harpreet SingheditedPosted Dec 27, 2012, 3:38 AMEdited Dec 27, 2012, 3:40 AM
Thanks for the informative post. I want to use regular expreession in the string "ABCDEF GH IGH (*)". The value in the bracket is a dynamic numeric value. How do I use regular expression in the above string to recogonize only the alphabets outside the bracket. Please advice.
Rajendra KokarePosted Oct 5, 2012, 9:29 AM
Thanks internal bool IsValidEmail(string EmailID) { string reg = @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$"; if (Regex.IsMatch(EmailID, reg)) { return true; } else { return false; } }
stefan stefanoveditedPosted Jun 15, 2011, 8:32 AMEdited Jun 16, 2011, 1:21 AM
I have html elements like & # 1 6 0 ; and & n b s p How can i remove these For the time being I am escaping html tags with this Regex "<[^>]*>"
vas mayeditedPosted Apr 21, 2011, 1:45 AMEdited Apr 21, 2011, 1:51 AM
hi, i need to do search engine, its like string matching, if the search string consists of boolean text like AND,OR,NOT i have to format the search string according to the boolean logic.. please help me.. Thanks in advance..
Rajib DasPosted Apr 5, 2011, 10:41 PM
Hi, Thanks for sharing such a nice resource of programming knowledge. it is a great source of learning programming. i've got a problem about regular expression. I've got a .dll file which provides me of diferent phone numbers according to area code like <01> 1234-5678. I've to use regular expression to display all phone numbers like this way: There are 3 phone numbers for the <03> area code. No: 1234-5678 No: 1234-6789 ... ... ... ... ... Can anyone please help me find the solution? Thanks Regards Rajib
TomPosted Jan 20, 2011, 12:18 AM
I have read your introduction, I find it very useful in your method. By the way, there is another way to do this, Spire.DataExport can export data from database. Now it's free for everyone, it's fast and stable. I hope it can help you. More information:http://www.e-iceblue.com/Introduce/free-dataexport-component.html
Srividhya ParthasarathyPosted Oct 26, 2010, 2:29 AM
Hi, I want to exclude decimal number while matching for numbers. Example. I want to match 1980. and not 1980.235 Pls help me out!!
Peter JPosted Oct 25, 2010, 3:23 PM
I'm a retired faculty teaching on line and have been asked to develop a text mining course for a body of students whose only programming language up to the time they take this course is C#. I'm familiar with using Perl so I'm hoping once I really learn C# and then the .NET regex classes I should be ok. I got Visual Studio and getting there with C#, but when I tried the Validation class I got errors under all underlined words in the following lines: using System.Text.RegularExpressions; Regex objAlphaPattern = new Regex("[^a-zA-Z]"); The error says: The type of namespace name 'RegularExpressions' could not be found (are you missing a using directive or an assembly reference?) I gather I'm using the correct using directive so I guess the second. Any suggestions welcome. If this is not a forum where such simplistic questions should be asked let me know - peter j
jeewanPosted Aug 9, 2010, 9:36 AM
hi pls help to find me Regex to remove leading zeros afetr decimal place. eg. 1.0 to 1 eg. 1.00 to 1 Thanks
MeshaPosted May 26, 2010, 1:22 PM
thank you very much
sreePosted Apr 12, 2010, 6:08 PM
Hi, I built the regular expression for a page directive for aspx page. Regex regDirective = new Regex("<%[\\s]*@[\\s]*[a-z|A-Z]+[\\s]+[[a-z|A-Z]+=\"[a-z|A-Z|0-9]*\"[\\s]*]+[\\s]+%[\\s]*>$"); But it is not matching it. eg for a page directive: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample,assembly1" Title="Sample Page Title" %> can anyone please help me with the regex for the above page directive. thanks, regards, sreelu
Sumesh NaireditedPosted Apr 2, 2010, 4:32 AMEdited Apr 2, 2010, 4:33 AM
The article provieded is Good.BUt I have question related to Regular Expression. What is the difference between mnx and mnxi?
Alejandro LopPosted Mar 20, 2010, 8:58 PM
Very good article, thanks! c# articles
mahesh diddiPosted Mar 1, 2010, 11:00 AM
can anyone help me with regular expression which has to be at least 8 characters with a mix of letters and numbers.
Osher EPosted Jan 26, 2010, 6:21 AM
You're doing a lot of redundent work. For instance - for the IsNumber - Simply try this pattern: "^([-])?[0-9]*[.]?[0-9][0-9]*$" tested against: tests should pass = "23423" ,"0.42342" ,"-2342.243" ,"+2342.243" ,"+.243" ,"-.243" ,"+0.243" ,"-0.243" ,"+1230.243" ,"-1230.243" tests should fail = "abc" ,"0.0.1" ,"234.234a" ,"234a" ,"23a4" ,"-2342.243e" ,"+-2342.243" ,"-+2342.243" ,"+-2342" ,"-+2342" ,"12-.32" ,"12-0.32" ,"." ,""
Gaurav AnandPosted Jul 27, 2009, 10:15 AM
HI Prasad, That was an excellent article. My requirement is Splitting the string 12a45b so that the resultant array has the values/Items =12 and 45 Which regular expression could we use for the same? Thanks & regards, Gaurav
vinay kumarPosted May 8, 2009, 5:33 AM
hi gud evng, i have a expression like "DYYMMDD' (ex:D091029).. so i want regular expression for this date model
JonPosted Dec 8, 2008, 1:32 PM
I have a string that contains alphanumerc and hyphens. I need to search the string and if it has a hyphen that has an integer on both sides keep the hyphen otherwise remove the hyphen. eg. the-dog12 becomes thedog12 or the1-2dog remains as the1-2dog
shikhar kapurPosted Jan 24, 2008, 4:09 AM
hi guys i need to make a method that takes a regular expression as input and creates random passwords of a particular length corresponding to the regular expression everytime it is called. Language m working on is c#,.NET Need this urgently Thanx
senthil velPosted Dec 18, 2007, 12:33 AM
hi, i am new to .Net. can any one say how to validate numeric and string alone.I used [0-9] for numeric and [a-zA-Z] for string. Pls mail me @ [email protected]
Bojtika bPosted Dec 14, 2007, 8:18 AM
I have searched a program in C# that can find the regular expressions in an opened file. I could find it in your article. So thank you. But I would have a question. how would you write in C# the next expression. This is a limited comment with ## terminals: ##((#|E)Not(#))*## and an other one: (+|-|E)D+.D+(E(+|-|E)D+|E) it a number with exponent. Pls help me as soon as possible.
Pulkit DubeyPosted Dec 6, 2007, 5:32 AM
Tell me what is session and why we use session in ASP.NET,and why we use session. Thanku
GrungeanPosted Dec 5, 2007, 4:18 AM
Thank you
Irfan MirzaPosted Nov 8, 2007, 4:03 AM
Hi, The code above have so many errors and requires a thorough review. Kindly remove it until you fix the issues. Examples: IsNaturalNumber(...) return true for 127.127 IsAlpha() return true for 12 and so many..... Thanks Irfan Mirza [email protected]
anil kadeditedPosted Nov 6, 2007, 12:16 PMEdited Nov 6, 2007, 12:25 PM
hi i want to replace the string starting with http:// and ending with / . for e.g. http://www.start.com/star/abcd/ fd http://helo/d I WANT IT AS p/star/abcd/ fd p/d IT WILL BE GREAT IF SOME ONE CAN HELP ME.
bassam mehanniPosted Aug 16, 2007, 7:21 PM
Hi I am trying to remove extra < b >,< /b > tags from a string, for example the string "< b >I < b > love< /b >< b > regular< /b > < b > expression< /b >< /b >" should become "< b >I love regular expressions< /b >" I added unnessecary spaces so that the tags would show Thanks Bassam
Sreekanth SurabhiPosted Jul 17, 2007, 1:40 AM
I need to seach for a patterns like "Pattern[one" or "Pattern[two" in a give string. How can i do this using regular expressions in C# .net. If i give a regular expression like.... Regex objNotNaturalPattern=new Regex("*Pattern[*"); It is treating [ as range pattern and throwing an error. Can some one suggest me how to do this? Thanks in advance.
micheal maryeditedPosted Jan 23, 2007, 10:47 PMEdited Jan 23, 2007, 10:51 PM
plz help me to finding list of links using "c#.Net" and regular expression. i need the common pattern that r used to extracting all the links. that means, if u given the google web site, it will get all the links like c#corner.com,codeproject.com and etc. plz any body help me.