ARTICLE

Regular Expressions Usage in C#

Posted by Prasad Articles | C# Language September 07, 2001
The source code shows how to use Regular Expressions in C#.
Reader Level:

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
Article Extensions
Contents added by nikhil sreeni on Dec 10, 2012
Download File: Validation.zip
post comment
     

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.

Posted by Harpreet Singh Dec 27, 2012

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;}}

Posted by Rajendra Kokare Oct 05, 2012

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 "<[^>]*>"

Posted by stefan stefanov Jun 15, 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..

Posted by vas may Apr 21, 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

Posted by Rajib Das Apr 05, 2011
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.