'Regex to replace all password with ***
I have the following json:
Data: {"Account":"d\\adm","Password":"cWExZjEiMTM="},"SqlServer":{"InstanceName":"","MachineName":"MyMachine","Port":null}
I would like to use RegExp to replace Password value with ***.
cWExZjEiMTM= => ***
In my example I'm expecting the following output:
Data: {"Account":"d\\adm","Password":"***"},"SqlServer":{"InstanceName":"","MachineName":"MyMachine","Port":null
I only have the following solution:
string invokeSpec = "\":{\"Account\":\"d\\\\adm\",\"password\":\"cWExZjEiMTM=\"},\"SqlServer\":{\"InstanceName\":\"\",\"MachineName\":\"MyMachine\",\"Port\":null}";
var pattern = "\\\"Password\\\":\\\"(?<pass>[^\\\"]*)\\\"";
var replaced = Regex.Replace(invokeSpec, pattern, "\"Password\":\"***\"", RegexOptions.IgnoreCase);
":{"Account":"d\\adm","Password":"***"},"SqlServer":{"InstanceName":"","MachineName":"MyMachine","Port":null}
Solution 1:[1]
As people said in the comment, if you can, use a JSON parser instead of regular expression. But let's dismiss that, since that's not the question.
You're capturing the wrong part of your input. What you want is a substitution.
string invokeSpec = "\":{\"Account\":\"d\\\\adm\",\"password\":\"cWExZjEiMTM=\"},\"SqlServer\":{\"InstanceName\":\"\",\"MachineName\":\"MyMachine\",\"Port\":null}";
var pattern = "(\\\"password\\\":\\\")[^\\\"]*(\\\")";
var replaced = Regex.Replace(invokeSpec, pattern, "$1***$2", RegexOptions.IgnoreCase);
As you can see, we're capturing two groups, the parts that the password is between of. So, there are 3 parts to the regular expression:
(\\\"password\\\":\\\")
=> Part to the left of the password[^\\\"]*
=> the password itself (note that in your example, you can replace this with the non-greedy.*?
)(\\\")
=> Part to the right of the password
And we're referencing them with $1
and $2
in the replace method, replacing the original password with ***
.
Solution 2:[2]
I suggest to use JObject
to replace the Password
var jObject = JObject.Parse(jsonString);
jObject["Password"] = "*****";
Console.WriteLine(jObject.ToString()); //save this value to log
Solution 3:[3]
String pass = "abc=gwdgjs, vhhhhycPassword.10.22.33.09.0=hsdfjs,hjghygh=uhh";
String passKeyStar = "";
String passKeyStar1 = "";
String keyValue[] = pass.split(",");
for(String t : keyValue) {
//passKeyStar = t;
if(t.contains("Password")){
passKeyStar1=t.split("=")[1];
}
}
System.out.println("replace text: "+pass.replaceAll(passKeyStar1, "******"));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Krishna Varma |
Solution 3 |