我用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
如何获得最后的匹配和最后的子匹配? (长度属性?)
关于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'!你在开玩笑吗?它只是一种方法吗?
是否有任何可能的方法来制作普通滤波器,而不是这种巨大的方法?
答案 0 :(得分: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
答案 1 :(得分: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
[/编辑]