RegExp class

Searches strings with a regular expression: finds the matches, tests for one, replaces them and splits a string at them.

RegExp is a replacement for the regular expression object of VBScript. It follows the same object model: Execute returns a MatchCollection of Match objects, and the indexes of both are zero-based. The matching is done by the vba-regex engine, which the package includes as the StaticRegex module.

The class is not predeclared. Create an instance with New, set Pattern and the options, then call a method.

Dim re As RegExp
Set re = New RegExp
re.Pattern = "(\d+)-(\d+)"
re.Global = True

Dim matches As MatchCollection
Set matches = re.Execute("10-20 and 30-40")
Debug.Print matches.Count                        ' 2
Debug.Print matches.Item(0).Value                ' 10-20
Debug.Print matches.Item(1).SubMatches.Item(0)   ' 30

Debug.Print re.Test("none")                      ' False
Debug.Print re.Replace("10-20", "$2-$1")         ' 20-10

Options

Four properties change how the pattern is matched. Flags reads and sets all four as one string of letters.

Property Flag When True
Global g All matches are used. When False, Execute, Replace and Split use only the first match.
MultiLine m ^ and $ also match at the start and end of each line.
IgnoreCase i Letter case is ignored.
DotAll s . also matches line terminators.

All four are False in a new instance.

Invalid patterns

The pattern is compiled the first time a method or one of IsValid, LastError and LastErrorNumber needs it. It is compiled again after Pattern or IgnoreCase is set to a different value. Global, MultiLine and DotAll are applied when a match is made and do not cause a new compilation.

A pattern that does not compile does not raise an error at once. IsValid returns False, and LastError and LastErrorNumber describe the failure. Execute, Test, Replace and Split then raise that error, with the number in LastErrorNumber, the description in LastError and the source RegExp.

Properties

  • DotAll – returns or sets whether . matches line terminators
  • Flags – returns or sets the four options as a string of letters
  • Global – returns or sets whether all matches are used
  • IgnoreCase – returns or sets whether letter case is ignored
  • IsValid – returns whether the pattern compiles
  • LastError – returns the message of the compile error
  • LastErrorNumber – returns the number of the compile error
  • MultiLine – returns or sets whether ^ and $ match at line boundaries
  • Pattern – returns or sets the regular expression

Methods

  • Execute – returns the matches in a string
  • Replace – replaces the matches in a string
  • Split – splits a string at the matches
  • Test – returns whether a string contains a match

See Also