萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 不區分大小寫關鍵字高亮:Instr 迴圈法與 RegExp 正則法完整對比

前言

在網頁中高亮顯示搜尋關鍵字是常見需求。挑戰在於:不區分大小寫匹配,且保留原文大小寫(如關鍵字 "bc",原文 "abcaBcabCaBC" 中的 "Bc"、"bC"、"BC" 皆需高亮,且保持原樣)。本文對比兩種實作:Instr 迴圈法與 RegExp 正則法。

方法一:Instr 迴圈法 (純 VBScript,無相依)

<%
Function HighLight_Instr(ByVal sourceText, ByVal keyword)
    Dim result, remaining, pos, matchLen, matchedText
    If keyword = "" Then HighLight_Instr = sourceText : Exit Function
    
    result = ""
    remaining = sourceText
    matchLen = Len(keyword)
    
    Do
        ' vbTextCompare (1) = 不區分大小寫
        pos = InStr(1, remaining, keyword, vbTextCompare)
        If pos = 0 Then Exit Do
        
        ' 1. 輸出匹配前的純文字
        result = result & Left(remaining, pos - 1)
        
        ' 2. 取得原文中實際匹配的片段 (保留原大小寫)
        matchedText = Mid(remaining, pos, matchLen)
        
        ' 3. 包裝高亮標籤
        result = result & "" & matchedText & ""
        
        ' 4. 剩餘字串右移繼續搜尋
        remaining = Mid(remaining, pos + matchLen)
    Loop
    
    ' 附加剩餘尾部
    HighLight_Instr = result & remaining
End Function
%>

方法二:RegExp 正則法 (更簡潔、效能更佳)

<%
Function HighLight_RegExp(ByVal sourceText, ByVal keyword)
    Dim re
    If keyword = "" Then HighLight_RegExp = sourceText : Exit Function
    
    Set re = New RegExp
    re.IgnoreCase = True   ' 不區分大小寫
    re.Global = True       ' 全域匹配
    re.Pattern = "(" & EscapeRegExp(keyword) & ")"  ' 捕獲組保留匹配文本
    
    ' $1 代表第一個捕獲組的內容 (即原文匹配片段)
    HighLight_RegExp = re.Replace(sourceText, "$1")
    Set re = Nothing
End Function

' 輔助:轉義正則特殊字元
Function EscapeRegExp(str)
    EscapeRegExp = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace( _
        str, "\", "\\"), ".", "\."), "*", "\*"), "+", "\+"), "?", "\?"), _
        "^", "\^"), "$", "\$"), "(", "\("), ")", "\)"), "[", "\["), "]", "\]")
End Function
%>

測試與輸出對比

<%
Dim testText, keyword
testText = "abcaBcabCaBCabcaBCa"
keyword = "bc"

Response.Write "原文:" & testText & "
" Response.Write "關鍵字:" & keyword & "

" Response.Write "Instr 法:" & HighLight_Instr(testText, keyword) & "
" Response.Write "RegExp 法:" & HighLight_RegExp(testText, keyword) & "
" %>

輸出結果 (兩者相同)

原文:abcaBcabCaBCabcaBCa
關鍵字:bc

Instr 法:abcaBcabCaBCabcaBCa

RegExp 法:abcaBcabCaBCabcaBCa

效能與適用性比較

維度Instr 迴圈法RegExp 正則法
代碼行數~20 行~10 行 (含轉義函數)
執行速度 (長文本)較慢 (字串重組開銷)快 (原生優化)
記憶體分配多次字串拼接產生臨時物件內部優化,分配較少
特殊字元處理無需轉義需轉義關鍵字中的正則元字元
相依性零 (核心 VBScript)需 VBScript.RegExp (IE/IIS 內建)
可維護性邏輯直觀,易除錯正則表達式需熟悉語法

進階需求:整詞匹配

若需「整詞匹配」(如關鍵字 "cat" 不匹配 "category"),正則法只需調整 Pattern:

re.Pattern = "\b(" & EscapeRegExp(keyword) & ")\b"  ' \b 為單詞邊界

Instr 法則需額外檢查匹配前後字元是否為非單詞字元,代碼複雜度顯著上升。

結語

對於經典 ASP 環境:

  • 簡單專案/短文本/關鍵字無特殊字元:RegExp 法優先,代碼簡潔、效能佳。
  • 關鍵字含正則元字元/極簡環境/教學示範:Instr 迴圈法零相依、邏輯透明。
  • 核心關鍵:**捕獲組 ($1) 保留原文大小寫**,這是兩種方法實現「不區分大小寫搜尋、保留原文顯示」的關鍵技巧。
copyright © 萬盛學電腦網 all rights reserved