将新值附加到Matchcollection

时间:2013-06-07 09:01:28

标签: vba ms-access-2010

我正在使用正则表达式,因为我想从文本文件中提取一些数据。例如,我想从我的文本文件中的这一行中提取每个数字:

ST/X   0.0000000000000000   6.4000000000000004   12.8000000000000010   19.1999999999999990   25.6000000000000010   32.0000000000000000

我在第一次使用这个正则表达式来找到 ST / X 来做到这一点:

regstx.Pattern = "(ST/X)\s*(-?[\d]*(\.)?[\d]*\s*)+"

然后我找到这个代码块的每个数字:

If matchstx.Count <> 0 And (swknnf = True Or swknl = True) Then
 Set matchxnum = regxnum.Execute(Mid(Trim(matchstx.Item(0)), 5))
End If

我像这样设置了regxnum:

regxnum.Pattern = "-?\d{1,}\.{0,1}\d{0,}"

它工作正常如果我只有一行STX,但如果我在eaxh之后有很多行的STX,那么就像这样:

ST/X   0.0000000000000000   6.4000000000000004   12.8000000000000010   19.1999999999999990   25.6000000000000010   32.0000000000000000   
ST/X   38.3999999999999990   44.7999999999999970   51.2000000000000030   57.6000000000000010   64.0000000000000000   70.4000000000000060 

我的想法不起作用,上面的代码重写了每个STX,但是我想在 matchxnum 中使用所有STX以某种方式我想这样做:

If matchstx.Count <> 0 And (swknnf = True Or swknl = True) Then
 Set matchxnum = matchxnum + regxnum.Execute(Mid(Trim(matchstx.Item(0)), 5))
End If

我怎样才能在VBA中实现这个想法,顺便说一下,我已经定义了像这样的matchxnum,我在VBA中使用了访问权限:

DIM matchxnum As MatchCollection
你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果您的问题是您正在为您处理的每个输入行覆盖matchxnum集合,那么一个简单的解决方案就是创建您自己的集合,并在每个matchxnum之后附加regxnum.Execute()成员。 {1}}打电话,就像这样

Dim fso As New FileSystemObject, ts As TextStream, tsLine As String
Dim regxnum As New RegExp, matchxnum As MatchCollection, matchxnumItem As match
Dim myCollection As New Collection, thing As Variant

Set ts = fso.OpenTextFile("C:\__tmp\stxTest.txt", ForReading)

regxnum.Pattern = "-?\d{1,}\.{0,1}\d{0,}"
regxnum.Global = True

Do While Not ts.AtEndOfStream
    tsLine = ts.ReadLine
    Set matchxnum = regxnum.Execute(Mid(Trim(tsLine), 5))
    For Each matchxnumItem In matchxnum
        '' append this group of matches to a separate Collection
        myCollection.Add matchxnumItem.Value
    Next
Loop

'' now dump the contents of myCollection to make sure the code worked
For Each thing In myCollection
    Debug.Print thing
Next