Skip to main content

Parsing Text with Regex (Function)

Hello Everyone,

This time, I have come up with another VBA code which parses the required stuff in the braces (.*) (assuming reader knows basis Regular Expression syntax). So straightaway, here is the code :-


       
Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp
   
    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.
       
        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If
       
    End With
End Function
       
 

Actually, its a VBA function which takes regex pattern as pattern and html as text stuff to be searched in for regex expression or pattern. Other explanations are commented out in the code.

Note:- Please add a reference to the Microsoft VBScript Regular Expressions 5.5 library from Tools >> References  in the VB Editor Window.

if you have any queries and improvements regarding it. Please comment below.

Regards,
Vikas Gautam

Comments