需求:test13@#esli → t**********i (首尾各 1 字元,其餘替換為 *)。用字串操作比正則更簡單高效。
Function MaskPassword(pwd)
If Len(pwd) <= 2 Then
MaskPassword = pwd ' 太短不遮罩或自行決定
Exit Function
End If
Dim first, last, midLen, masked
first = Left(pwd, 1)
last = Right(pwd, 1)
midLen = Len(pwd) - 2
masked = first & String(midLen, "*") & last
MaskPassword = masked
End Function
' 測試
MsgBox MaskPassword("test13@#esli") ' 輸出 t**********i
Function MaskPasswordReg(pwd)
Dim re
Set re = New RegExp
re.Global = True
re.Pattern = "(?<=.).(?=.)" ' 非首非尾的任意字元 (需支援 lookaround)
' VBScript RegExp 不支援 lookbehind,改用替換邏輯:
' 實際上 VBScript 正則功能弱,不建議用於此場景
MaskPasswordReg = pwd
End Function
注意: VBScript (ASP 經典) 的 RegExp 物件**不支援**前瞻/後顧斷言 ((?=), (?<=)),故無法用單一正則完成「保留首尾」替換。字串函數 Left/Right/String 是原生、高效、相容的選擇。
public static string MaskPassword(string pwd) {
if (string.IsNullOrEmpty(pwd) || pwd.Length <= 2) return pwd;
return pwd[0] + new string('*', pwd.Length - 2) + pwd[pwd.Length - 1];
}
用最簡單的字串操作解決遮罩需求,將精力集中在真正的安全防護上。