I'm trying to create a regular expression in C# that will replace the password of a connection string so that it is not shown when I display it on a page. The connection string password are somewhere in the string as PWD=password;
So far I have:
Regex.Replace(connStr, "PWD=.*;", "PWD=********");
This works to find the beginning of the pattern, but the problem is the wild card (.*) is also including the ; so the pattern is never terminated and the remainder of the string is replaced too. How can I say everthing but a ; in my RegEx?
Thanks.
You don't need to use RegEx for this - .NET has the built-in SqlConnectionStringBuilder class which you can use to get values from the connection string and change them.
Example code:
string conString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;";
var builder = new SqlConnectionStringBuilder(conString);
builder.Password = "********";
Console.WriteLine(builder.ToString());
You can use a non-greedy quantifier:
PWD=.*?;
Or exclude ;
s:
PWD=[^;]*;
Here is the regex I'm using
(?<=Password=).+?(?=(;|'|"|$))
With positiv look behind to find the start of the password, positiv look ahead to find the end of the Password and a not greedy match Expression. The "Detektion Tokens" (Password= ;'"$) might differ in varios scenarios.
Testcases: https://regex101.com/
c# implementation
using System.Text.RegularExpressions;
private static Regex _regex = new Regex("(?<=Password=).+?(?=(;|'|\"|$))");
//...
var decryptPwdMatch = _regex.Match("some connectionstring for example");
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With