Regex in C#
Regex in C#
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]+$");