[英]Replace a part of string containing Password
有点类似于这个问题 ,我想替换argv
内容:
string argv = "-help=none\n-URL=(default)\n-password=look\n-uname=Khanna\n-p=100";
对此:
"-help=none\n-URL=(default)\n-password=********\n-uname=Khanna\n-p=100"
我尝试了非常基本的字符串查找和搜索操作(使用IndexOf
, SubString
等)。 我正在寻找更优雅的解决方案,以替换字符串的这一部分:
-password=AnyPassword
至:
-password=*******
并保持字符串的其他部分不变。 我在寻找String.Replace
或Regex
替换是否有帮助。
我尝试过的(错误检查不多):
var pwd_index = argv.IndexOf("--password=");
string converted;
if (pwd_index >= 0)
{
var leftPart = argv.Substring(0, pwd_index);
var pwdStr = argv.Substring(pwd_index);
var rightPart = pwdStr.Substring(pwdStr.IndexOf("\n") + 1);
converted = leftPart + "--password=********\n" + rightPart;
}
else
converted = argv;
Console.WriteLine(converted);
此代码用几个"*"
字符替换密码值:
string argv = "-help=none\n-URL=(default)\n-password=look\n-uname=Khanna\n-p=100";
string result = Regex.Replace(argv, @"(password=)([\s\S]*?\n)",
match => match.Groups[1].Value + new String('*', match.Groups[2].Value.Length - 1) + "\n");
您也可以删除new String()
部分,并将其替换为字符串常量
与Rubens Farias的解决方案类似,但更为优雅:
string argv = "-help=none\n-URL=(default)\n-password=\n-uname=Khanna\n-p=100";
string result = Regex.Replace(argv, @"(password=)[^\n]*", "$1********");
它从字面上匹配password=
,将其存储在捕获组$1
并保持匹配,直到达到\\n
。
但是,这将产生恒定数量的*
。 但是,无论如何,告诉一个密码多少字符可能已经向黑客传达了太多信息。
工作示例: https : //dotnetfiddle.net/xOFCyG
( // Store the following match in capture group $1.
password= // Match "password=" literally.
)
[ // Match one from a set of characters.
^ // Negate a set of characters (i.e., match anything not
// contained in the following set).
\n // The character set: consists only of the new line character.
]
* // Match the previously matched character 0 to n times.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.