我正试图在vba中计算和收集所有找到的正则表达式匹配。你可以在这里看到我的进展,但问题是计数不起作用。收集匹配后,我必须检查如果值不在以下列表中:
PAGE_BREAK; NEW_LINE; EMPTY_LINE; FS:; / FS:; B; / B; COLOR:;整数取代; / COLOR:; IMAGE:
BY变量表中有。匹配只是带括号的值,除了上面的例子。这里有一些截图:
Sub simpleRegex()
Dim strPattern As String: strPattern = "\<.*?\>"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range
Dim match As Object
Dim newArray() As Integer
Set Myrange = Sheets("BY Blocks").Range("D10:D12")
For Each cell In Myrange
If strPattern <> "" Then
strInput = cell.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
MsgBox ("A cell match with the pattern: ") & strPattern
Else
MsgBox ("No cell match with the pattern: ") & strPattern
End If
Set objMatches = regEx.Execute(strInput)
For Each match In objMatches '
a = match.SubMatches.Count
For i = 0 To a - 1
MsgBox match.SubMatches.Item(i) 'display each group
Next
Next
Set objReg = Nothing
End If
Next
End Sub
答案 0 :(得分:0)
您正在使用的正则表达式不提供子匹配 - 仅匹配。如果您想要子匹配,则需要在表达式中添加一些括号。如果不是 - 只需迭代匹配集合
答案 1 :(得分:0)
我并不完全清楚你在做什么,正如在其他答案中所指出的那样,你没有检索子匹配,因为正则表达式中没有应用任何组,但这里是匹配的数量,忽略你列出的项目。我也打印到每个比赛接受和拒绝的即时窗口。
<强>代码:强>
Option Explicit
Public Sub simpleRegex()
Dim strPattern As String: strPattern = "\<.*?\>"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range
Dim currMatch As match
Set Myrange = ThisWorkbook.Worksheets("BY Blocks").Range("D1:D7")
Dim ignoreItems()
ignoreItems = Array("<PAGE_BREAK>", "<NEW_LINE>", "<EMPTY_LINE>", "<FS:>", "</FS:>", "<b>", "</b>", "<COLOR:>", "<integer>", _
"</COLOR:>", "<IMAGE:>")
Dim currCell As Range
For Each currCell In Myrange
If strPattern <> vbNullString Then
strInput = currCell.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
'
' If regEx.Test(strInput) Then
' MsgBox ("A cell match with the pattern: ") & strPattern
' Else
' MsgBox ("No cell match with the pattern: ") & strPattern
' End If
Dim objMatches As MatchCollection, counter As Long
Set objMatches = regEx.Execute(strInput)
Dim matchRange As Range
Set matchRange = ThisWorkbook.Worksheets("BY Variables").Range("A1:A4") '<== Change as appropriate
For Each currMatch In objMatches
If IsError(Application.match(currMatch, ignoreItems, 0)) Then
Debug.Print "Accept: " & currMatch
counter = counter + 1
If Not IsError(Application.match(currMatch, matchRange, 0)) Then MsgBox currMatch
Else
Debug.Print "Reject: " & currMatch
End If
Next currMatch
Set regEx = Nothing
End If
Next currCell
MsgBox "# matches accepted = " & counter
End Sub
立即窗口:
<强> MSGBOX:强>
输入数据: