根据文本文件的单词搜索文件

时间:2011-09-11 11:38:18

标签: search vbscript words

我想在文本文件中同时搜索多个单词。

例如,我想要搜索这3个单词:Majid,superuser,device

通常我应该逐个搜索它们,而且我不能同时搜索所有这些。所以我想在文本文件中同时搜索这些单词。

我想在文本文件中输入这3个单词,每行一个单词。我们将它命名为SearchText。现在我有一个目标文本,我想在其中搜索这些单词。我们将它命名为TargetText。

我想告诉应用程序或类似内容从SearchText获取单词并在TargetText中找到它们并突出显示它们或给我找到结果。

我希望我很清楚。那么有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

你很清楚。我认为最好的选择是Regex。
试试这个:

Option Explicit
Dim oFso        : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim srcPath     : SrcPath = oFso.GetParentFolderName(WScript.ScriptFullName)
Dim sWordList   : sWordList = ofso.OpenTextFile(oFso.BuildPath(srcPath, "search.txt")).ReadAll()
Dim sTargFile   : sTargFile = ofso.OpenTextFile(oFso.BuildPath(srcPath, "target.txt")).ReadAll()
Dim strWords    : strWords = Join(Split(sWordList, vbCrLf), "|")
Dim oReg        : Set oReg = New RegExp
Dim oDict       : Set oDict = CreateObject("Scripting.Dictionary") 'for found words
oDict.CompareMode = vbTextCompare 'case insensitive

With oReg
    .Global = True
    .IgnoreCase = True
    .Pattern = "("& strWords &")" ' (word1|word2|word3|etc..)
    'if the words contain some special chars for regex, you may need to escape with \ char
    'see the information below: http://goo.gl/cqGVp
    Dim collFND : Set collFND = oReg.Execute(sTargFile)
    Dim Fnd
    'WScript.Echo String(50, "-")
    For Each Fnd In collFND
        With Fnd
            'WScript.Echo "Word : "& .Value, ", Position: ("& .FirstIndex &","& .Length &")"
            oDict(.Value) = ""
        End With
    Next
    Set collFND = Nothing
    'WScript.Echo String(50, "-"), vbCrLf, "Higlighted Output:", oReg.Replace(sTargFile, "[$1]")
    ofso.CreateTextFile(oFso.BuildPath(srcPath, "foundwords.txt"),True).Write(Join(oDict.Keys, vbCrLf)) 'found words saved
End With