MS VB For Application - 读取txt文件中的href值

时间:2015-12-02 23:48:54

标签: regex vba

我的txt文件(links.txt)包含以下几个链接

<A HREF="file1.oft">File 1</A>
<A HREF="file2.oft">File 2</A>
<A HREF="file3.oft">File 3</A>
<A HREF="file4.oft">File 4</A>
<A HREF="file5.oft">File 5</A>

我需要的是打开文件并读取链接的值(文件1,文件2等)

我该怎么做?正则表达式?我想这很简单但我能找到我需要完成的事情。

??? strRegX = "<\s*A(.|\n)*?\s*>((.|\n)*?)<\s*\/A\s*>"  ?????

Const ForReading = 1
Set objTextFile = objFSO.OpenTextFile("links.txt", ForReading)
Do Until objTextFile.AtEndOfStream
***** CODE GOES HERE ******
Loop

提前致谢!

1 个答案:

答案 0 :(得分:0)

我真的很讨厌正则表达式。我会做更多“旧式”:

Option Explicit

Private Sub showLinks()
    Dim content As String
    Dim pos As Integer

    ' read file content
    content = readFile("C:\Temp\links.txt")

    ' search for links
    Do While InStr(content, "<A HREF")
        ' find begin of link
        pos = InStr(content, "<A HREF")
        content = Mid(content, pos + 7)

        ' find closing >
        pos = InStr(content, ">")
        content = Mid(content, pos + 1)

        ' find begin of closing tag
        pos = InStr(content, "<")

        ' print out link text
        Debug.Print Left(content, pos - 1)
    Loop
End Sub

Private Function readFile(ByVal pFile As String) As String
    Dim ret As String
    Dim row As String

    ' create file handle
    Dim hnd As Integer
    hnd = FreeFile

    ' open file
    Open pFile For Input As hnd

    ' read file
    Do Until EOF(hnd)
        Line Input #hnd, row
        ret = ret & row
    Loop

    ' close file
    Close hnd

    ' return content
    readFile = ret
End Function

当然,显示概念有点简化。它需要可靠的错误处理,例如,以确保释放文件句柄,例如。但它应该只让你知道它是如何工作的。

您也可以使用FSO来读取文件(或者也可能是ADO)......但是我想告诉您,没有任何外部库就可以,因为这通常会导致问题。