0

I need to grab the value of password from db connection string using regex.

This is my current regex .*;(?i)Password=([^;]*). This works only if there is not any ; character in password.

add key="myKey" value="Data Source=MyDataSource;Initial Catalog=MyDB;User ID=test-user;Password=pA&-pass; unicode=True"

But it fails if there is ; character in password

add key="myKey" value="Data Source=MyDataSource;Initial Catalog=MyDB;User ID=test-user;Password=pass>; unicode=True"
Ward
  • 2,799
  • 20
  • 26
istudent
  • 105
  • 1
  • 11

1 Answers1

1

Brief

There will always be ways for your code to break since someone can create a password such as ;Password= such that your string is actually ;Password=;Password=;.

Assuming that is not possible (and also assuming it's not possible for someone to use similar variations such as portions of the password being in the following format ;s= where s is any word or space character), this should work for you.


Code

See regex in use here

(?<=;Password=)(?:(?!;[\w ]+=).)*

Results

Input

add key="myKey" value="Data Source=MyDataSource;Initial Catalog=MyDB;User ID=test-user;Password=pA&-pass; unicode=True"
add key="myKey" value="Data Source=MyDataSource;Initial Catalog=MyDB;User ID=test-user;Password=pass&gt;; unicode=True"

Output

pA&-pass
pass&gt;

Explanation

  • (?<=;Password=) Positive lookbehind ensuring what precedes matches ;Password literally
  • (?:(?!;[\w ]+=).)* Tempered greedy token matching any character, but ensuring it doesn't match ;, followed by any word or space characters, followed by =
ctwheels
  • 21,901
  • 9
  • 42
  • 77
  • 1
    Nice one, even matches if the password is the last property of the connection string. – Ward Jan 02 '18 at 16:27
  • Thank you sir. I will let you know if this work. ;Password=;Password=; There is the possibility for it to be happened. – istudent Jan 02 '18 at 16:46
  • @istudent If you want everything preceding `;Password=` (and including it) you can use `.*;Password=` instead of `(?<=;Password=)`. You may also want to place the entire tempered greedy token inside a capture groups such that your pattern is `.*;Password=((?:(?!;[\w ]+=).)*)` – ctwheels Jan 02 '18 at 17:32