函式用途
InStrRev 回傳子字串 最後一次 出現的位置 (從字串結尾往前搜尋),常用於:
- 解析檔案路徑取得檔名 (
\ 或 / 最後位置)
- 擷取副檔名 (最後一個
. 位置)
- 移除字串尾部特定標記
語法與參數
InStrRev(string1, string2[, start[, compare]])
| 參數 | 必要 | 說明 |
| string1 | 是 | 被搜尋的完整字串 |
| string2 | 是 | 要尋找的子字串 |
| start | 否 | 搜尋起始位置,預設 -1 (字串末尾);若含 Null 則報錯 |
| compare | 否 | 比較模式:0=vbBinaryCompare(二進位/區分大小寫,預設)、1=vbTextCompare(文字/不區分大小寫)、2=vbDatabaseCompare(資料庫規則) |
傳回值規則
| 條件 | 傳回值 |
| string1 為空字串 | 0 |
| string1 為 Null | Null |
| string2 為空字串 | start 值 |
| string2 為 Null | Null |
| 未找到 string2 | 0 |
| 找到 | 字元位置 (1-based,從字串開頭算起) |
| start > Len(string2) | 0 |
實戰範例
範例 1:取得檔名 (含副檔名)
Dim fullPath, pos, fileName
fullPath = "C:\Inetpub\wwwroot\images\photo.jpg"
pos = InStrRev(fullPath, "\")
If pos > 0 Then
fileName = Mid(fullPath, pos + 1) ' photo.jpg
End If
Response.Write fileName
範例 2:只取副檔名
Dim extPos, ext
extPos = InStrRev(fileName, ".")
If extPos > 0 Then
ext = Mid(fileName, extPos + 1) ' jpg
End If
範例 3:移除尾部標記
Dim html, tagPos
html = "<div>內容</div><div>更多</div>設計園地"
tagPos = InStrRev(html, "</div>")
If tagPos > 0 Then
' 保留最後一個 </div> 之前的內容
html = Left(html, tagPos - 1)
End If
Response.Write html
' 輸出:<div>內容</div><div>更多
範例 4:不區分大小寫搜尋
Dim pos
pos = InStrRev("ABCabcABC", "abc", -1, vbTextCompare) ' 傳回 7 (第2組ABC的位置)
' 若用 vbBinaryCompare (預設) 則傳回 4 (第一組abc的位置)
InStr vs InStrRev 比較
| 特性 | InStr | InStrRev |
| 搜尋方向 | 左→右 (開頭往後) | 右→左 (結尾往前) |
| 參數順序 | InStr([start,] string1, string2) | InStrRev(string1, string2[, start]) |
| 預設 start | 1 (開頭) | -1 (結尾) |
| 典型用途 | 找第一次出現 | 找最後一次出現 |
注意事項
- 位置回傳值皆為 1-based (第一個字元位置為 1),配合
Mid、Left、Right 使用時無需調整。
- 若
string2 為空字串,InStrRev 回傳 start (預設 -1 會轉為字串長度+1),邏輯上需特別處理。
- 效能:對超長字串搜尋尾部特徵時,
InStrRev 比反轉字串用 InStr 快得多。
總結
InStrRev 是處理路徑、副檔名、尾部標記移除等「從後往前」搜尋需求的利器。掌握其參數順序、compare 模式與傳回值規則,能寫出更簡潔健全的字串處理程式碼。