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.
Can you use
SqlConnectionto parse the connection string for you and avoid the RegEx? If you just need the data base name, the following should work:EDIT
A better way to do this was provided by Allon Guralnek – Thanks!
Use
SqlConnectionStringBuilderfor this – it will extract any information you need.