在網頁中高亮顯示搜尋關鍵字是常見需求。挑戰在於:不區分大小寫匹配,且保留原文大小寫(如關鍵字 "bc",原文 "abcaBcabCaBC" 中的 "Bc"、"bC"、"BC" 皆需高亮,且保持原樣)。本文對比兩種實作:Instr 迴圈法與 RegExp 正則法。
<%
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
%>
<%
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
關鍵字:bcInstr 法:abcaBcabCaBCabcaBCa
RegExp 法:abcaBcabCaBCabcaBCa
| 維度 | Instr 迴圈法 | RegExp 正則法 |
|---|---|---|
| 代碼行數 | ~20 行 | ~10 行 (含轉義函數) |
| 執行速度 (長文本) | 較慢 (字串重組開銷) | 快 (原生優化) |
| 記憶體分配 | 多次字串拼接產生臨時物件 | 內部優化,分配較少 |
| 特殊字元處理 | 無需轉義 | 需轉義關鍵字中的正則元字元 |
| 相依性 | 零 (核心 VBScript) | 需 VBScript.RegExp (IE/IIS 內建) |
| 可維護性 | 邏輯直觀,易除錯 | 正則表達式需熟悉語法 |
若需「整詞匹配」(如關鍵字 "cat" 不匹配 "category"),正則法只需調整 Pattern:
re.Pattern = "\b(" & EscapeRegExp(keyword) & ")\b" ' \b 為單詞邊界
Instr 法則需額外檢查匹配前後字元是否為非單詞字元,代碼複雜度顯著上升。
對於經典 ASP 環境: