gpt4 book ai didi

regex - VBA 文本文件搜索

转载 作者:行者123 更新时间:2023-12-01 11:01:02 27 4
gpt4 key购买 nike

我正在尝试编写一个 VBA 程序,用于在文本文件中搜索用户名以查找用户的 IP 地址。因此,例如,给定以下输入,如果我搜索 Chris Trucker,我想在消息框中看到 192.168.130.22

> 192.168.2.151,Super Fly,ABC\Flys,2012-05-18 16:11:29 
> 192.168.2.200,Rain,ABC\rain,2012-05-17 15:42:05
> 192.168.2.210,Snow,ABC\Snow,2012-05-16 08:24:39
> 192.168.2.78,Wind,ABC\wind,2012-05-02 19:24:06
> 192.168.130.21,Mike Jordan,ABC\Jordanm,2012-05-18 17:28:11
> 192.168.130.22,Chris Trucker,ABC\Truckerc,2012-05-18 17:28:11
> 192.168.130.23,Chris Jackson,ABC\JacksonC,2012-05-18 17:04:39

尝试了以下但它是 VBScript

Const ForReading = 1

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "JacksonC"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("\\server\tsusers\Users.txt", ForReading)

Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
osakapc = Left(strSearchString,14)
Set colMatches = objRegEx.Execute(strSearchString)

If colMatches.Count = 1 Then
For Each strMatch in colMatches


Next
End If
Loop

最佳答案

这是我的做法:

Option Explicit

Sub tester()
Dim inputFilePath As String
inputFilePath = "\\server\tsusers\Users.txt"

MsgBox GetUserIpAddress("Chris Trucker", inputFilePath)
' or "JacksonC" or "Bozo" or whatever

End Sub

Function GetUserIpAddress(whatImLookingFor As String, _
inputFilePath As String)
Const ForReading = 1

Dim foundIt As Boolean
Dim thisLine As String
Dim ipAddress As String
Dim FSO As Object
Dim filInput As Object

Set FSO = CreateObject("Scripting.FileSystemObject")
Set filInput = FSO.OpenTextFile(inputFilePath, ForReading)

foundIt = False
Do Until filInput.AtEndOfStream
thisLine = filInput.ReadLine
If InStr(thisLine, whatImLookingFor) <> 0 Then
foundIt = True
ipAddress = Replace((Split(thisLine, ",")(0)), "> ", "")
Exit Do
End If
Loop

If foundIt Then
GetUserIpAddress = ipAddress
Else
Err.Raise 9999, , _
"I stiiiiiiiill haven't foooouuuund what I'm looking for."
End If
End Function

如您所见,如果找不到用户名,此函数会抛出错误。

请注意,此功能允许您搜索长格式 (Chris Trucker) 或短格式 (Truckerc) 甚至时间戳 ( 2012-05-18 17:28:11)。但请注意,如果您的搜索词有多个实例,则只会返回与第一个实例对应的 IP 地址。如果您希望返回所有实例,则可以调整代码。

作为最后的评论,建议始终声明所有变量,并通过在代码顶部使用 Option Explicit 来强制自己这样做。

关于regex - VBA 文本文件搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10713780/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com