Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » C# Language » Regular Expressions Usage in C#

Regular Expressions Usage in C#

The source code shows how to use Regular Expressions in C#.

Page Views : 1520155
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Description 

The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.

Explanation of Regular Expressions:

Regular expressions are used to search specified in the source string.

Examples:

Pattern#1
Regex objNotNaturalPattern=new Regex("[^0-9]");

Pattern#2 
Regex objNaturalPattern=new Regex("0*[1-9][0-9]*"); 

Pattern#1 will match for strings other than 0 to 9.^ symbol is used for Specifying not condition.[] brackets if we are to give range values such as 0 - 9 or a-z or A-Z 

eg. abc will return true

123 will return false.   

Pattern#2 will match for string which are Natural Numbers.Natural numbers Are numbers which are always greater than 0.The pattern 0* tells that a natural Number can be prefixed with any number of zero's or no zero's.the next [1-9] tells that it should contain atleast one number from 1 to 9 followed by any numbers of

0-9's 

Eg. 0007 returns true whereas 00 will return false. 

Basic things to be understood in RegEx: 

"*" matches 0 or more patterns
"?" matches single character
"^" for ignoring matches.
"[]" for searching range patterns.

More RegEx patterns in Next Article. 

Source Code:

// 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

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Prasad
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Regular expression "c#.Net" by micheal On January 23, 2007
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. 
Reply | Email | Modify 
Re: Regular expression "c#.Net" by micheal On January 23, 2007

hi frnds,

             thanz for trying the result. i got the answer. the pattern is

 

r = new Regex(@"<A[^>]*?HREF\s*=\s*[""']?([^'"" >]+?)[ '""]?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

Regards

Micheal

 

Reply | Email | Modify 
Search for special characters using regular expressions by Sreekanth On July 17, 2007
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.
Reply | Email | Modify 
Re: Search for special characters using regular expressions by vamsi On August 7, 2007

Hai [ is a special character so please use escape charecter to avoid that error.Else create a string like the new Regex(@"Pattern[*"); this will solve your problem

Reply | Email | Modify 
removing extra html tags by bassam On August 16, 2007
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
Reply | Email | Modify 
replacing using Regex.Replace by anil On November 6, 2007

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.

Reply | Email | Modify 
Correction Required! by Irfan On November 8, 2007
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 irfanmirza@gmail.com
Reply | Email | Modify 
Thank you by Grungean On December 5, 2007
Thank you
Reply | Email | Modify 
Session by Pulkit On December 6, 2007
Tell me what is session and why we use session in ASP.NET,and why we use session. Thanku
Reply | Email | Modify 
thank you by Bojtika On December 14, 2007
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.
Reply | Email | Modify 
hi, by senthil On December 18, 2007
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 @ senthilvel.s@quintegrasolutions.com
Reply | Email | Modify 
Re: hi, by william On January 21, 2008

validate !!!

[A-Z][0-9]{2-11}

Reply | Email | Modify 
Random password using regular expression by shikhar On January 24, 2008
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
Reply | Email | Modify 
help by Jon On December 8, 2008
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
Reply | Email | Modify 
date regular expression by vinay On May 8, 2009
hi gud evng,

i have a expression like "DYYMMDD' (ex:D091029).. so i want regular expression for this date model
Reply | Email | Modify 
Re: date regular expression by Kirtan On May 8, 2009
Date Regular Expression

is Here


(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}
Reply | Email | Modify 
Regex Help by Darnell On October 25, 2010
I have question regarding regex


        Regex r = new Regex.("^[123456789ABCD]");
        var tempEvents = (from x in List.Events
                               where r.IsMatch(x.Code)
                               select new
                               {
                                 Code= x.eTag,
                                 Data= x.eValue
                               }).ToList();

I want to add to the regex  above looking  "Apple", "Oranges", "green"

How to add the string to the regex, whats the correct syntax for strings
Reply | Email | Modify 
Splitting the string 12a45b by Gaurav On July 27, 2009
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
Reply | Email | Modify 
redundent work by Osher On January 26, 2010
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"
       ,"."
       ,""
 
Reply | Email | Modify 
Re: redundent work by Ali On February 11, 2010

Use this tool if you'd like to experiment with C# regular expressions.

Reply | Email | Modify 
regular exp help plzz by mahesh On March 1, 2010
can anyone help me with regular expression which has to be at least 8 characters with a mix of letters and numbers.
Reply | Email | Modify 
Thanks by Alejandro On March 20, 2010
Very good article, thanks!

Reply | Email | Modify 
Question Related to Reg Ex by Sumesh On April 2, 2010
The article provieded is Good.BUt I have question related to Regular Expression.
What is the difference between mnx and mnxi?
Reply | Email | Modify 
Regular expression for a page directive by sree On April 12, 2010
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

Reply | Email | Modify 
thanks alot by Mesha On May 26, 2010

thank you very much

Reply | Email | Modify 
Need help - Regex to remove trailing zeros by jeewan On August 9, 2010
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

Reply | Email | Modify 
Regex Help by Darnell On October 25, 2010
I have question regarding regex


        Regex r = new Regex.("^[123456789ABCD]");
        var tempEvents = (from x in List.Events
                               where r.IsMatch(x.Code)
                               select new
                               {
                                 Code= x.eTag,
                                 Data= x.eValue
                               }).ToList();

I want to add to the regex  above looking  "Apple", "Oranges", "green"

How to add the string to the regex, whats the correct syntax for strings
Reply | Email | Modify 
Re: Need help - Regex to remove trailing zeros by Niladri On November 15, 2010
You can simply type cast to int for the result
Reply | Email | Modify 
setting up a text mining course using C# by Peter J On October 25, 2010
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
Reply | Email | Modify 
Re: setting up a text mining course using C# by Peter J On October 25, 2010
maybe I should have mentioned that I'm running 64-bit Vista and had to load .NET 2.0 since 4.0 would not install - could that be the source of the problem? - peter j
Reply | Email | Modify 
Exclude decimal numbers using regex in c sharp by Srividhya On October 26, 2010
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!!
Reply | Email | Modify 
Data export by Tom On January 20, 2011
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
Reply | Email | Modify 
Regular Expression by Rajib On April 5, 2011
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
Reply | Email | Modify 
c# regular expression search, format the search prase if boolean AND,OR,NOT presents by vas On April 21, 2011
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..
Reply | Email | Modify 
Remove html formatting and tags by stefan On June 15, 2011
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 "<[^>]*>"
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.