1

我使用 VBA 编写了一个简单的脚本。(我需要用excel优化一些工作)。

关于正则表达式的第一个问题:

正如我之前所说,我使用了 VBA。

简单的任务:获取模式匹配并捕获子匹配。

我的代码是:

Dim ResStr as Object
Dim LastStr as Object
Dim RE as Object


Set RE = CreateObject("vbscript.regexp") 'create a regex
With RE
    .MultiLine = False  'm-key
    .Global = False     'g-key
    .IgnoreCase = False 'i-key
    .Pattern = "[<]TD\s+class=gm[>](\d+\.\d+)[<][/]TD[>]" 'tag
End With

Set ResStr = RE.Execute(StrDollar)  'use regex  
Set LastStr = ResStr(0).SubMatches  'get submatch

如何获得 LAST 匹配和 LAST 子匹配?(长度属性?)

关于 Dir 函数的第二个问题:

如何过滤文件?

我在msdn上看到了这段代码:

   ' Display the names in C:\ that represent directories.
   MyPath = "c:\"   ' Set the path.
   MyName = Dir(MyPath, vbDirectory)   ' Retrieve the first entry.
   Do While MyName <> ""   ' Start the loop.
     ' Use bitwise comparison to make sure MyName is a directory.
     If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then
       ' Display entry only if it's a directory.
       Debug.WriteLine(MyName)
     End If   
     MyName = Dir()   ' Get next entry.
  Loop

If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then- 停止'msdn-guy'!你在开玩笑吗?它只有一种方法吗?

有没有办法制作普通的过滤器,而不是这种巨大的线法?

4

2 回答 2

3

要获得所有匹配项、子匹配项、长度等,您将使用类似这样的内容 - 我添加了一个工作示例,其中包含一个更简单的模式来演示(即,将数字序列与非数字匹配)

您应该Test在假定已找到匹配项之前使用您的正则表达式以避免错误

Sub Test()
Dim RE As Object
Dim strSample As String
Dim ResStr As Object
Dim LastStr As Object
strSample = "123dd6789a"
Set RE = CreateObject("vbscript.regexp")    'create a regex
With RE
    .MultiLine = False  'm-key
    .Global = True     'g-key
    .IgnoreCase = False    'i-key
    .Pattern = "\d+([^\d])"
End With
If RE.Test(strSample) Then
    Set ResStr = RE.Execute(strSample)
    For Each LastStr In ResStr
        MsgBox "Match: " & LastStr & vbNewLine & "SubMatch: " & LastStr.submatches(0) & vbNewLine & "Position: " & LastStr.firstindex + 1 & vbNewLine & "Length: " & LastStr.Length
    Next
End If
End Sub
于 2012-05-03T10:35:08.170 回答
1

问题 1

你可以试试这个:

Sub Test(StrDollar)
Dim LastStr As Object
Dim RE As New RegExp
Dim mt As Match


With RE
    .MultiLine = False  'm-key
    .Global = True     'g-key
    .IgnoreCase = False 'i-key
    .Pattern = "<TD\s+class=gm>(\d+\.\d+)</TD>" 'tag
    For Each mt In .Execute(StrDollar)
         Set LastStr = mt.SubMatches  'get submatch
    Next mt
End With

MsgBox LastStr(0)

End Sub

问题 2

也许dir()函数无法根据扩展名制作文件列表。

[编辑]

Sub Test2(StrDollar)
Dim LastStr As Object
Dim RE As New RegExp
Dim mt As Match
Dim dic As New Scripting.Dictionary 'scripting runtime
Dim pos&

With RE
    .MultiLine = False  'm-key
    .Global = True     'g-key
    .IgnoreCase = False 'i-key
    .Pattern = "<TD\s+class=gm>(\d+\.\d+)</TD>" 'tag
    For Each mt In .Execute(StrDollar)
        pos = pos + 1
        dic.Add CStr(pos), mt.FirstIndex & "||" & mt.Value & "||" & mt.SubMatches(0)
    Next mt
End With

MsgBox dic.item(CStr(pos))

End Sub

[/编辑]

于 2012-05-03T10:30:07.760 回答