Skip to content

RegExp2

Laurent Franceschetti edited this page Sep 15, 2018 · 5 revisions

A module for manipulating Regular Expressions

There is indeed a standard library, but unfortunately it was written in the spirit of a system library: to be as general as possible... which is often the opposite as user friendly, since a user has a particular use case. That is why it needs a wrapper for daily use in vba.

Hint: to develop your regular expression, you could use an online tool, e.g. : https://regex101.com/

Dependencies

  • Libraries: Microsoft VB Script Regular Expressions

Code

See the module source.

Usage

Get the first match of a string

Signature

Here is the signature:

Function RegMatch(ByVal sourceString As String, Pattern As String, _
Optional IgnoreCase = True, Optional Multiline = False) As String

Example

a = RegMatch("Hello world", "world")
Debug.Print a
b = RegMatch("Hello world", "^\w*")
Debug.Print b

Will return:

world
Hello

Replace a pattern

Signature

Function RegReplace(sourceString As String, Pattern As String, ReplaceVar As String, _
Optional IgnoreCase = True, Optional GlobalReplace = True, Optional Multiline = False) As String

Get all matches

Signature

Function RegMatches(sourceString As String, Pattern As String, _
Optional IgnoreCase = True, Optional Multiline = False) As MatchCollection

Example 1

The result is a collection, which is also indexed.

In the Immediate window:

Debug.Print Regmatches("Hello world this is a wonderful.", "wo\w*")(1)
wonderful

Example 2

Here is an example from the source code:

Sub TestRegMatches(sourceString As String, Pattern As String)
' Test Regmatches; you can use it as example, or a debug tool for your regular expressions.
    Dim myMatch As Match
    For Each myMatch In RegMatches(sourceString, Pattern)
        Debug.Print "Found " & myMatch.Value
    Next
End Sub