Regular Expressions using VB.NET

In this article I will explain you about the Regular Expressions in VB.NET.
  • 6698
 

A regular expression is a string of characters that contains a pattern to find the string or strings you are looking for. In its simplest form, a regular expression is just a word or phrase to search for in the source string. Regular expressions include meta characters which are special characters that add a great deal of flexibility and convenience to the search.

Regular expressions have their origins in automata theory and formal language theory, which study models of computation automata and ways to describe and classify formal languages. In theoretical computer science, a formal language is nothing but a set of strings.

In the 1940s, two mathematicians, Warren McCulloch and Walter Pitts, described the nervous system by modeling neurons. Later, mathematician Stephen Kleene described these models using his mathematical notation called regular sets and developed regular expressions as a notation for describing them.

Afterward, Ken Thompson, one of the key creators of the Unix Operating System, built regular expressions into Unix-based text tools like qed, (predecessor of the Unix ed) and grep. Since then, regular expressions have been widely used in Windows and Unix.

Patterns

Let's examine two regular expression patterns:

Pattern#1
Dim objNotNaturalPattern As New Regex("[^0-9]")
Pattern #2 Dim objNaturalPattern As New Regex("0*[1-9][0-9]*")

Pattern #1 will match for strings other than those containing numbers from 0 to 9 (^ = not). (Use brackets to give range values, such as 0â€"9, aâ€"z, or Aâ€"Z.) For example the string abc will return true when you apply the regular expression for pattern #1, but the string 123 will return false for this same pattern.

Pattern #2 will match for strings that contain only natural numbers (numbers that are always greater than 0). The pattern 0* indicates that a natural number can be prefixed with any number of zeroes or no zeroes at all. The next pattern, [1-9], means that it should contain at least one integer between 1 and 9 (including 1 and 9). The next pattern, [0-9]*, indicates that it should end with any number of integers between 0 and 9. For example, 0007 returns true, whereas 00 returns false.

The example given below shows the code for validating strings entered against various regular expression patterns.

Example of Regular Expressions

    Imports System.Text.RegularExpressions
    Imports System

    Class Validation
        Public Shared Sub Main()
            Dim strToTest As [String]
            Dim objValidate As New Validation()
            Console.Write("Enter a String to Test for Natural Numbers:")
            strToTest =
Console.ReadLine()

            If objValidate.IsNaturalNumber(strToTest) Then
                Console.WriteLine("{0} is a Valid Natural Number", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Natural Number", strToTest)
            End If

            Console.Write("Enter a String to Test for Whole Numbers:")
            strToTest =
Console.ReadLine()
            If objValidate.IsWholeNumber(strToTest) Then
                Console.WriteLine("{0} is a Valid Whole Number", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Whole Number", strToTest)
            End If

            Console.Write("Enter a String to Test for Integers:")
            strToTest =
Console.ReadLine()
            If objValidate.IsInteger(strToTest) Then
                Console.WriteLine("{0} is a Valid Integer", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Integer", strToTest)
            End If

            Console.Write("Enter a String to Test for Positive Numbers:")
            strToTest =
Console.ReadLine()
            If objValidate.IsPositiveNumber(strToTest) Then
                Console.WriteLine("{0} is a Valid Positive Number", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Positive Number", strToTest)
            End If

            Console.Write("Enter a String to Test for Numbers:")
            strToTest =
Console.ReadLine()
            If objValidate.IsNumber(strToTest) Then
                Console.WriteLine("{0} is a Valid Number", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Number", strToTest)
            End If

            Console.Write("Enter a String to Test for Alpha Numerics:")
            strToTest =
Console.ReadLine()
            If objValidate.IsAlphaNumeric(strToTest) Then
                Console.WriteLine("{0} is a Valid Alpha Numeric", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Alpha Numeric", strToTest)
            End If

            Console.Write("Enter a String to Test for Alphabets:")
            strToTest =
Console.ReadLine()
            If objValidate.IsAlpha(strToTest) Then
                Console.WriteLine("{0} is a Valid Alpha String", strToTest)
            Else
                Console.WriteLine("{0} is not a Valid Alpha String", strToTest)
            End If

        End
Sub

        ' Function to test for Positive Integers
        Public Function IsNaturalNumber(ByVal strNumber As [String]) As Boolean
            Dim
objNotNaturalPattern As New Regex("[^0-9]")
            Dim objNaturalPattern As New Regex("0*[1-9][0-9]*")
            Return Not objNotNaturalPattern.IsMatch(strNumber) AndAlso objNaturalPattern.IsMatch(strNumber)
        End Function

        ' Function to test for Positive Integers with zero inclusive
        Public Function IsWholeNumber(ByVal strNumber As [String]) As Boolean
            Dim
objNotWholePattern As New Regex("[^0-9]")
            Return Not objNotWholePattern.IsMatch(strNumber)
        End Function

        ' Function to Test for Integers both Positive & Negative
        Public Function IsInteger(ByVal strNumber As [String]) As Boolean
            Dim
objNotIntPattern As New Regex("[^0-9-]")
            Dim objIntPattern As New Regex("^-[0-9]+$|^[0-9]+$")
            Return Not objNotIntPattern.IsMatch(strNumber) AndAlso objIntPattern.IsMatch(strNumber)
        End Function

        ' Function to Test for Positive Number both Integer & Real
        Public Function IsPositiveNumber(ByVal strNumber As [String]) As Boolean
            Dim
objNotPositivePattern As New Regex("[^0-9.]")
            Dim objPositivePattern As New Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$")
            Dim objTwoDotPattern As New Regex("[0-9]*[.][0-9]*[.][0-9]*")
            Return Not objNotPositivePattern.IsMatch(strNumber) AndAlso objPositivePattern.IsMatch(strNumber) AndAlso Not objTwoDotPattern.IsMatch(strNumber)
        End Function

        ' Function to test whether the string is valid number or not
        Public
Function IsNumber(ByVal strNumber As [String]) As Boolean
            Dim
objNotNumberPattern As New Regex("[^0-9.-]")
            Dim objTwoDotPattern As New Regex("[0-9]*[.][0-9]*[.][0-9]*")
            Dim objTwoMinusPattern As New Regex("[0-9]*[-][0-9]*[-][0-9]*")
            Dim strValidRealPattern As [String] = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"
            Dim strValidIntegerPattern As [String] = "^([-]|[0-9])[0-9]*$"
            Dim objNumberPattern As New Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")")
            Return Not objNotNumberPattern.IsMatch(strNumber) AndAlso Not objTwoDotPattern.IsMatch(strNumber) AndAlso Not objTwoMinusPattern.IsMatch(strNumber)             AndAlso
            objNumberPattern.IsMatch(strNumber)
        End Function

        ' Function To test for Alphabets.
        Public Function IsAlpha(ByVal strToCheck As [String]) As Boolean
            Dim
objAlphaPattern As New Regex("[^a-zA-Z]")
            Return Not objAlphaPattern.IsMatch(strToCheck)
        End Function

        ' Function to Check for AlphaNumeric.
        Public Function IsAlphaNumeric(ByVal strToCheck As [String]) As Boolean
            Dim
objAlphaNumericPattern As New Regex("[^a-zA-Z0-9]")
            Return Not objAlphaNumericPattern.IsMatch(strToCheck)
        End Function
    End
Class

Output

re1.gif
 

Conclusion

Hope this article would have helped you in understanding the Regular Expressions in VB.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.