Discussion:
|
This entry builds on the excellent work by VBAX member brettdj in:
"Using Regular Expressions (RegExp) in Excel"
http://vbaexpress.com/kb/getarticle.php?kb_id=68
These functions, RegExpFind and RegExpReplace, are very useful for text-parsing tasks where you can define a rule for the text you are seeking, but those rules are not easily supported by the usual text-handling functions such as Left, Right, Mid, InStr, InStrRev, and Replace.
This entry shows how to encapsulate RegExp.Find and RegExp.Replace into UDFs that can be implemented very quickly to support either building worksheet formulas in Excel, or to support code in a VB/VBA project.
RegExpFind returns either an array with all matching substrings, a specific substring based on position number, or the last matching substring, depending on the value of the Pos argument; if no match is found, the function always returns an empty string, regardless of the setting for the Pos argument. RegExpReplace returns a string where all matching substrings in the LookIn string are replaced or just the first matching substring is replaced, depending on the value of the ReplaceAll argument. (If there are no matches, RegExpReplace simply returns the original LookIn string.)
This entry is rated as 'Hard' for 'Ease of Use' only because mastering RegExp pattern strings can be difficult at first; adding the code itself to your project is not difficult.
Several primers are available online, such as at:
http://www.regular-expressions.info/reference.html
or by searches at www.google.com or www.msdn.com
|
Option Explicit
Function RegExpFind(LookIn As String, PatternStr As String, Optional Pos, _
Optional MatchCase As Boolean = True)
Dim RegX As Object
Dim TheMatches As Object
Dim Answer() As String
Dim Counter As Long
If Not IsMissing(Pos) Then
If Not IsNumeric(Pos) Then
RegExpFind = ""
Exit Function
Else
Pos = CLng(Pos)
End If
End If
Set RegX = CreateObject("VBScript.RegExp")
With RegX
.Pattern = PatternStr
.Global = True
.IgnoreCase = Not MatchCase
End With
If RegX.test(LookIn) Then
Set TheMatches = RegX.Execute(LookIn)
If IsMissing(Pos) Then
ReDim Answer(0 To TheMatches.Count - 1) As String
For Counter = 0 To UBound(Answer)
Answer(Counter) = TheMatches(Counter)
Next
RegExpFind = Answer
Else
Select Case Pos
Case 0
RegExpFind = TheMatches(TheMatches.Count - 1)
Case 1 To TheMatches.Count
RegExpFind = TheMatches(Pos - 1)
Case Else
RegExpFind = ""
End Select
End If
Else
RegExpFind = ""
End If
Set RegX = Nothing
Set TheMatches = Nothing
End Function
Function RegExpReplace(LookIn As String, PatternStr As String, Optional ReplaceWith As String = "", _
Optional ReplaceAll As Boolean = True, Optional MatchCase As Boolean = True)
Dim RegX As Object
Set RegX = CreateObject("VBScript.RegExp")
With RegX
.Pattern = PatternStr
.Global = ReplaceAll
.IgnoreCase = Not MatchCase
End With
RegExpReplace = RegX.Replace(LookIn, ReplaceWith)
Set RegX = Nothing
End Function
|