[算表]請教如何用正則表達式提取txt那兩個關鍵字
軟體:MS office
版本:2007
各位版友:下午好
請教如何提取示例中的如圖所示的關鍵字,返回excel到sheet1 A1和B1
如圖所示:http://ppt.cc/mx-l
示例文件下載: http://ppt.cc/ODqz
我先說說我的寫法發信人后面那個到很好匹配直接寫成
Pattern = "發信人: ([A-Za-z]\w+)"
但下面一個IP 如果寫成FROM: ([^]]*),就找錯了位置,找成了123.128.1.*,但我真正
需要的是222.128.189.*
它的路徑必須是"--"后面那個IP,我最終要找到內容就是FROM后面那個IP。--在文本中
一定是在占用某行的第一個和第二個位置。
我目前的寫法是:
Sub 提取IP()
Dim r%, i%
Dim arr, brr(1 To 100000, 1 To 2)
Dim mypath$, myname$
Dim reg(1 To 2) As New RegExp
With reg(1)
.Global = True
.Pattern = "發信人: ([A-Za-z]\w+)"
End With
With reg(2)
.Global = True
.Pattern = "FROM: ([^]]*)"
End With
mypath = "C:數據\"
If Dir(mypath & "合并源結果.txt") = "" Then
MsgBox "合并源結果.txt不存在!"
Exit Sub
End If
Open "C:結果.txt" For Input As #1
arr = Split(StrConv(InputB(LOF(1), #1), vbUnicode), vbLf)
Close #1
m = 0
For i = 0 To UBound(arr)
If reg(1).TEST(arr(i)) Then
m = m + 1
Set mh = reg(1).Execute(arr(i))
brr(m, 1) = mh(0).SubMatches(0)
ElseIf reg(2).TEST(arr(i)) Then
Set mh = reg(2).Execute(arr(i))
brr(m, 2) = mh(0).SubMatches(0)
End If
Next
With Worksheets("sheet5")
.UsedRange.Offset(1, 0).ClearContents
.Range("A2").Resize(UBound(brr), UBound(brr, 2)) = brr
End With
End Sub
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.38.52.129
※ 文章網址: https://www.ptt.cc/bbs/Office/M.1426495254.A.589.html
→
03/16 17:03, , 1F
03/16 17:03, 1F
→
03/16 17:04, , 2F
03/16 17:04, 2F
※ 編輯: yyingx (27.38.52.129), 03/16/2015 18:48:22
→
03/16 18:48, , 3F
03/16 18:48, 3F
→
03/16 18:49, , 4F
03/16 18:49, 4F
→
03/16 18:49, , 5F
03/16 18:49, 5F
→
03/16 18:54, , 6F
03/16 18:54, 6F
→
03/16 18:54, , 7F
03/16 18:54, 7F
→
03/16 18:55, , 8F
03/16 18:55, 8F
→
03/16 18:59, , 9F
03/16 18:59, 9F
Office 近期熱門文章
PTT數位生活區 即時熱門文章