三大核心場景
- 驗證:測試字串是否符合模式 (電話、信用卡、Email、身分證)
- 替換:標識特定文字並刪除或替換 (清理舊資料、轉換標籤)
- 提取:依模式擷取子字串 (解析日誌、抓取欄位)
場景一:資料驗證
Function ValidatePhone(phone)
Dim re
Set re = New RegExp
re.Pattern = "^\d{2,3}-\d{7,8}$" ' 區碼-號碼
ValidatePhone = re.Test(phone)
End Function
場景二:批量替換 HTML 標籤
Function CleanHtml(html)
Dim re
Set re = New RegExp
re.Pattern = "<script[^>]*>.*?</script>"
re.Global = True
re.IgnoreCase = True
re.MultiLine = True
CleanHtml = re.Replace(html, "")
End Function
場景三:從日誌提取 IP 與時間
Function ParseLogLine(line)
Dim re, matches, result
Set re = New RegExp
re.Pattern = "(\d+\.\d+\.\d+\.\d+).*\[(.*?)\]"
re.Global = True
Set matches = re.Execute(line)
If matches.Count > 0 Then
result = Array(matches(0).SubMatches(0), matches(0).SubMatches(1))
Else
result = Array("", "")
End If
ParseLogLine = result
End Function
效能優勢
- 單一表達式完成多步字串操作 (搜尋+切分+替換)
- VBScript 原生字串函數 (
InStr, Mid, Replace) 需多行代碼且易出錯
- 正則引擎內部優化 (NFA/DFA) 處理大量文本更高效
適用建議
- 靜態文本簡單搜尋:
InStr/Replace 足矣
- 動態模式、結構化提取、複雜驗證:正則表達式為首選
- 跨語言專案:正則模式可直接移植 (JS、VBScript、VBA、C#、Python 大同小異)