1

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

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,但如果我有很多排 STX 在 eaxh 之后,它可以正常工作,如下所示:

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,但是我想以某种方式将所有 STX 放在matchxnum中:

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

你能帮我解决这个问题吗?

4

1 回答 1

1

如果您的问题是matchxnum您处理的每个输入行都将覆盖您的集合,那么一个简单的解决方案是创建您自己的集合并matchxnum在每次regxnum.Execute()调用后将其成员附加到其中,如下所示

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
于 2013-06-07T10:54:57.727 回答