Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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#.

Total page views :  914739
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


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


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
Thank you by Grungean On December 5, 2007
Thank you
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
Re: hi, by william On January 21, 2008

validate !!!

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

Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.