2015-12-02 42 views
0

我的txt文件(links.txt)中含有多個鏈接如下MS VB對於應用 - 一個TXT文件閱讀href的值

<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 

在此先感謝!

+0

類似這樣的表達應該給你你可以在代碼中輕鬆閱讀的組:'\ [[AZ] + [A-Za-z] + =「([a-zA-Z0-9] + [。 ] * [a-zA-Z0-9] +)「\>。*' – Harsh

回答

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)......但我想告訴你,沒有任何外部庫是可能的,因爲這經常會導致問題。

+0

謝謝。我不得不適應它,但它可以很好地完成我所需要的。非常感謝 :-) – JustQn4