2

How do I write a regular expression to retrieve password from connection string.

Connection string is like this:

USER ID=system;PASSWORD = ab;DATA ..

or

USER ID=system;PASSWORD=ab;DATA ...

or

USER ID=system;PASSWORD =ab;DATA...

or

USER ID=system;PASSWORD= ab;DATA ...

Tried the approach of using ConnectionStringBuilder. Works for SQL Server. But in case of Oracle it throws this exception:

Invalid length for connection option 'Data Source', maximum length is 128.

The Oracle Connection String:

USER ID=sa;PASSWORD=abc;DATA SOURCE="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.1)(PORT = 8080))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = Orcl)))"
9
  • 1
    So password never contains semicolon or spaces? Commented Sep 4, 2012 at 20:46
  • 1
    It may be easier to use the SqlConnectionStringBuilder class: msdn.microsoft.com/en-us/library/… Commented Sep 4, 2012 at 20:48
  • 1
    Stackoverflow is not for write me my code Commented Sep 4, 2012 at 20:48
  • 1
    whathaveyoutried.com Commented Sep 4, 2012 at 20:51
  • 1
    var password = new SqlConnectionStringBuilder("USER ID=system;PASSWORD =ab;").Password; one liner :p Commented Sep 4, 2012 at 21:07

2 Answers 2

9

Is there a requirement that you have to use a regular expression ? .NET has the functionality built in:

var sb = new SqlConnectionStringBuilder("USER ID=system;PASSWORD =ab;");
Console.WriteLine(sb.Password);

This is likely to be more robust than using a regular expression for that. The rules for the fields are rather comprehensive, and it is easy to make a Regex that will work for most connectionstrings, but will fail on some. See the connection string rules for a list of the rules that must be embedded in such a Regex.

Sign up to request clarification or add additional context in comments.

Comments

1

Regex:

.*PASSWORD[ ]*=[ ]*([^;]+)

6 Comments

Semicolons are allowed in the password
So where is the stop of the password then. I don't know how semicolons are escaped in your connection string.
Using regex when the connection string contains escaping with ' makes it nearly impossible. So don't use regex at all for it.
is the string ;DATA ... allowed in the password? or PASSWORD= allowed as an id?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.