-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmodRegEx.bas
79 lines (69 loc) · 2.53 KB
/
modRegEx.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Attribute VB_Name = "modRegEx"
Option Explicit
' Simple regex tools for linting / converting
Private mRegEx As Object
Private Property Get RegEx() As Object
If mRegEx Is Nothing Then Set mRegEx = CreateObject("vbscript.regexp"): mRegEx.Global = True
Set RegEx = mRegEx
End Property
' Return true/false if regex pattern `Find` is found in `Src`.
Public Function RegExTest(ByVal Src As String, ByVal Find As String) As Boolean
On Error Resume Next
RegEx.Pattern = Find
RegExTest = RegEx.test(Src)
End Function
' Return number of instances of pattern `Find` in `Src`.
Public Function RegExCount(ByVal Src As String, ByVal Find As String) As Long
On Error Resume Next
RegEx.Pattern = Find
RegEx.Global = True
RegExCount = RegEx.Execute(Src).Count
End Function
Public Function RegExNPos(ByVal Src As String, ByVal Find As String, Optional ByVal N As Long = 0) As Long
On Error Resume Next
Dim RegM As Object, tempStr As String, tempStr2 As String
RegEx.Pattern = Find
RegEx.Global = True
RegExNPos = RegEx.Execute(Src).Item(N).FirstIndex + 1
End Function
Public Function RegExNMatch(ByVal Src As String, ByVal Find As String, Optional ByVal N As Long = 0) As String
On Error Resume Next
Dim RegM As Object, tempStr As String, tempStr2 As String
RegEx.Pattern = Find
RegEx.Global = True
RegExNMatch = RegEx.Execute(Src).Item(N).Value
End Function
Public Function RegExReplace(ByVal Src As String, ByVal Find As String, ByVal Repl As String) As String
On Error Resume Next
Dim RegM As Object, tempStr As String, tempStr2 As String
RegEx.Pattern = Find
RegEx.Global = True
RegExReplace = RegEx.Replace(Src, Repl)
End Function
Public Function RegExSplit(ByVal szStr As String, ByVal szPattern As String) As Variant
On Error Resume Next
Dim oAl As Variant, oRe As Variant, oMatches As Variant
Set oRe = RegEx
oRe.Pattern = "^(.*)(" & szPattern & ")(.*)$"
oRe.IgnoreCase = True
oRe.Global = True
Set oAl = CreateObject("System.Collections.ArrayList")
Do While True
Set oMatches = oRe.Execute(szStr)
If oMatches.Count > 0 Then
oAl.Add oMatches(0).SubMatches(2)
szStr = oMatches(0).SubMatches(0)
Else
oAl.Add szStr
Exit Do
End If
Loop
oAl.Reverse
RegExSplit = oAl.ToArray
End Function
Public Function RegExSplitCount(ByVal szStr As String, ByVal szPattern As String) As Long
On Error Resume Next
Dim T() As Variant
T = RegExSplit(szStr, szPattern)
RegExSplitCount = UBound(T) - LBound(T) + 1
End Function