Split 是 ASP 處理結構化字符串的利器。本文通過實戰案例,從基礎語法到巢狀拆解,全方位掌握 Split 技巧。
aryReturn = Split("字符串", "分割符")
' 返回:基於 0 的一維數組
<%
Dim strURL, aryReturn, aryTemp, strUsername, strPassword, strServer
strURL = "ftp://username:password@server"
' 第一層:按冒號分割
aryReturn = Split(strURL, ":")
' 結果:aryReturn(0)="ftp" aryReturn(1)="//username" aryReturn(2)="password@server"
' 提取 username:去除 "//"
strUsername = Right(aryReturn(1), Len(aryReturn(1)) - 2)
' 第二層:按 @ 分割 password@server
aryTemp = Split(aryReturn(2), "@")
strPassword = aryTemp(0)
strServer = aryTemp(1)
Response.Write "用戶:" & strUsername & "<br>"
Response.Write "密碼:" & strPassword & "<br>"
Response.Write "伺服器:" & strServer
%>
<%
Dim str, ary
str = "ftp://username:password@server,https://user:pass@host"
' 以 ",https://" 為分割符,分割出兩個完整 URL
ary = Split(str, ",https://")
' ary(0) = "ftp://username:password@server"
' ary(1) = "user:pass@host" (注意:分割符本身被移除)
%>
' ❌ 錯誤:ReDim 不能用於 Split 返回值接收
' ReDim aryReturn ' 錯誤!
' ✅ 正確:直接賦值,VBScript 自動處理數組創建
Dim aryReturn
aryReturn = Split(str, ",")
ary = Split("abcdef", "|")
' 返回單元素數組:ary(0) = "abcdef", UBound(ary) = 0
' 可用 IsArray(ary) 驗證,永遠返回 True
If IsArray(aryReturn) Then
For i = LBound(aryReturn) To UBound(aryReturn)
Response.Write "元素[" & i & "] = " & aryReturn(i) & "<br>"
Next
End If
' 將多種分隔符統一為單一分隔符
str = Replace(str, ";", ",")
str = Replace(str, ",", ",")
ary = Split(str, ",")
Function ParseCSVLine(line)
' 簡易版:假設無換行、無雙引號嵌套
Dim inQuote, current, result, i, ch
inQuote = False
current = ""
ReDim result(0)
Dim idx : idx = 0
For i = 1 To Len(line)
ch = Mid(line, i, 1)
If ch = """" Then
inQuote = Not inQuote
ElseIf ch = "," And Not inQuote Then
ReDim Preserve result(idx)
result(idx) = current
idx = idx + 1
current = ""
Else
current = current & ch
End If
Next
ReDim Preserve result(idx)
result(idx) = current
ParseCSVLine = result
End Function
Split 會分配新數組與字符串副本,大字符串 (>100KB) 重複調用會有壓力RegExp 或 組件化處理Join 可實現數組↔字符串雙向轉換熟練掌握 Split + Replace + Join 三劍客,應付 95% 字符串結構化處理需求。