假设我有以下字符串:
"/encryption:aes128 /password:<PASSWORDHERE> /log:log.txt"
我需要将其写入日志文件,但需要屏蔽密码(例如替换为星号)。
我可以用几行代码轻松地做到这一点String.IndexOf
,String.Replace
但我很想看看其他人如何实现这一点,以便代码尽可能短和简洁。单行替换功能将是最好的。
我的目标是了解/学习一些组合字符串函数的新技术。
请注意,我对使用 RegEx 不感兴趣。
我不会向您展示单线,因为正如 Andrew 已经指出的那样,这将是不可理解的。
您坚持使用非正则表达式方法:
Dim input As String = "/encryption:aes128 /password:htzrj584372 /log:log.txt"
Dim pwdStart As Integer = input.IndexOf("password:")
If pwdStart <> -1 Then
Dim pwdEnd As Integer = input.IndexOf(" /log:", pwdStart)
If pwdEnd <> -1 Then
pwdStart += "password:".Length
Dim pwdLength = pwdEnd - pwdStart
Dim pwd = input.Substring(pwdStart, pwdLength)
Dim logText = input.Replace("password:" & pwd, "password:*****")
End If
End If
请注意,如果密码本身包含/log:
. 只有之前的部分会被屏蔽,因为我不知道密码的实际长度。
与 Andrew Barber 的想法相反,这很好用,并且假设具有阅读代码的基本能力是完全可以理解的。你可能想打开一个教科书安迪男孩。
假设:
strArgs = "/encryption:aes128 /password:<PASSWORDHERE> /log:log.txt"
然后:
strArgs = strArgs.Replace(strArgs.Substring(strArgs.IndexOf("/password:") + 10, strArgs.IndexOf(" /log:log.txt") - strArgs.IndexOf("/password:") - 10), "********")