Example 1 - Extracting real numbers from a line of text.
This example assumes we are going to read in lines of text that contain multiple floating point numbers separated by commas. The problem to overcome is that of reading each of the numbers while ignoring the commas that separate them. Using PatternPro, we can easily create a solution to the problem. The following VB code accomplishes our task.
Public Function ReadFloats( MyInput as String, Ret() as Double) as Integer
Dim rgx as new rxRegex, More as Boolean
' No numbers read yet
ReDim Ret(0)
' Set the regular expression pattern
rgx.Pattern = "[-+]?(([0-9]+)|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?)"
' Locate the first match
More = rgx.FindFirst(MyInput)
While More
' make room for another match
ReDim Ret(Ubound(Ret)+1)
Ret(Ubound(Ret)) = CDbl(rgx.MatchString)
' locate the next match
More = rgx.FindNext
Wend
' return the number of floats we just read
ReadFloats = Ubound(ret)
End Function
Example 2: Validating a variable name.
You need to validate a variable name the user has entered. The name must follow the rule that it begin with a letter followed by any number of letters, digits or an underscore. We can accomplish this task with only 3 lines of code using PatternPro.
Public Function ValidateName(Name as String) as Boolean
Dim rgx as New rxRegex
rgx.Pattern = "[a-zA-Z][a-zA-Z0-9_]*"
ValidateName = rgx.FindString(Name)
End Function
Example 3: Substitution using rxRegex
You need to cycle through some text and make sure that any hexadecimal value is represented in all uppercase letters. The catch is that you're going to look for Visual Basic and C style notation, and replace them with a standard all uppercase VB notation. The code to accomplish this using PatternPro follows.
Public Function SubstituteHex(Text as String) as Boolean
Dim rgx as New rxRegex, More As Boolean
rgx.Pattern = "(0[xX])|(&[hH])[0-9a-fA-F]+"
More = rgx.FindFirst(Text)
While More
rgx.Substitute( "&H" & UCase( Right(rgx.MatchString, rgx, MatchLength - 2) ) )
More = rgx.FindNext
Wend
End Function
Note: In the examples above, the patterns supplied to the regular expression engine contain numerous implicit loops, conditional and Boolean operations. There can be little doubt that if you wrote the example functions without the benefit of PatternPro you would have to write far more code.