[英]Replace a part of string containing Password
Slightly similar to this question , I want to replace argv
contents: 有点类似于这个问题 ,我想替换argv
内容:
string argv = "-help=none\n-URL=(default)\n-password=look\n-uname=Khanna\n-p=100";
to this: 对此:
"-help=none\n-URL=(default)\n-password=********\n-uname=Khanna\n-p=100"
I have tried very basic string find and search operations (using IndexOf
, SubString
etc.). 我尝试了非常基本的字符串查找和搜索操作(使用IndexOf
, SubString
等)。 I am looking for more elegant solution so as to replace this part of string: 我正在寻找更优雅的解决方案,以替换字符串的这一部分:
-password=AnyPassword
to: 至:
-password=*******
And keep other part of string intact. 并保持字符串的其他部分不变。 I am looking if String.Replace
or Regex
replace may help. 我在寻找String.Replace
或Regex
替换是否有帮助。
What I've tried (not much of error-checks): 我尝试过的(错误检查不多):
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);
This code replaces the password value by several "*"
characters: 此代码用几个"*"
字符替换密码值:
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");
You can also remove the new String()
part and replace it by a string constant 您也可以删除new String()
部分,并将其替换为字符串常量
Similar to Rubens Farias' solution but a little bit more elegant: 与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********");
It matches password=
literally, stores it in capture group $1
and the keeps matching until a \\n
is reached. 它从字面上匹配password=
,将其存储在捕获组$1
并保持匹配,直到达到\\n
。
This yields a constant number of *
's, though. 但是,这将产生恒定数量的*
。 But telling how much characters a password has, might already convey too much information to hackers, anyway. 但是,无论如何,告诉一个密码多少字符可能已经向黑客传达了太多信息。
Working example: https://dotnetfiddle.net/xOFCyG 工作示例: 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.