1

I have written a regex to match section of an SQL Connection string. In the first spec, the Initial Catalog etc. were forced not to contain special characters. So I had

string strConn = "Data Source=VAIOE;Initial Catalog=SomeTextOnlyCatname;Integrated 
    Security=True;Persist Security Info=True;MultipleActiveResultSets=True;Connect Timeout=0;";
Regex databaseNameRegex =
    new Regex(@"(?i)\b(Initial\sCatalog|Database)\b\s?=\s?(\w+\s*)*;?");

Now, I need to match sections which could have names with symbols, punctuation etc. For example

string strConn = "Data Source=VAIOE;Initial Catalog=N3wC@t@l0gName*6Symbols;Integrated 
    Security=True;Persist Security Info=True;MultipleActiveResultSets=True;Connect Timeout=0;";

where I want to return Initial Catalog=N3wC@t@l0gName*6Symbols.

I have tried

Regex databaseNameRegex =
    new Regex(@"(?i)\b(Initial\sCatalog|Database)\b\s?=\s?(\w+\p{P}*\p{M}*\p{Z}*\s*)*;?");

but this fails, due to the presence of semi-colons in the connection string. What is the best regex to deal with this?

Thanks for your time.

1 Answer 1

10

Can you use SqlConnection to parse the connection string for you and avoid the RegEx? If you just need the data base name, the following should work:

var conn = new SqlConnection(strConn);
Console.WriteLine(conn.Database);

EDIT

A better way to do this was provided by Allon Guralnek - Thanks!

Use SqlConnectionStringBuilder for this - it will extract any information you need.

var connBuilder = new SqlConnectionStringBuilder(strConn);
Console.WriteLine(connBuilder.InitialCatalog);
Sign up to request clarification or add additional context in comments.

3 Comments

I'd actually use the SqlConnectionStringBuilder class, which will provide access to all the key-value pairs inside a connection string. It will also let you construct a connection string from key-value pairs. So to get the Initial Catalog you can use new SqlConnectionStringBuilder(myConnectionString).InitialCatalog.
This is a great idea. I think I will use the SqlConnectionStringBuilderClass.
Well then, that is convenient!

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.