views:

81

answers:

4

Hi All,

<add key="Key1" value="Provider=SQLOLEDB.1;data source=serveripaddress;Initial Catalog=DB1;user id=uid;Password=***"/>

I gave the above string,I want to get the serveripaddress,DB1,uid and **** these values from that string.

+2  A: 
data source=([^;]*);Initial Catalog=([^;]*);user id=([^;]*);Password=([^;"]*)

You then have the matches in groups 1 to 4. If you get bored you can name the groups; helps readability of the code, though rarely helps readability of the regex itself.

Joey
thank you very much
subramani
+1 since subramani only says thank you, and never heard of accepting or voting up apparently
Peter
+1  A: 

Isn't it easier to split value using ';' char and then split every item by '=' char?

This way your connection string could be edited by users and even item order could be changed.

Michał Niklas
+6  A: 

Don't use a regex.

Parse the connection string using SqlConnectionStringBuilder and then access the keys from that.

var b = new SqlConnectionStringBuilder(myConnectionString);
var dataSource = b["Data Source"]; 
// etc.

Much easier, more maintainable and more reliable.

Greg Beech
+1  A: 

There is no need to parse a connection string when the BCL can do it for you:

var builder = new OleDbConnectionStringBuilder(connectionString);
var provider = builder.Provider;
var dataSource = builder.DataSource;
var initialCatalog = builder["Initial Catalog"];
var userID = builder["User ID"];
var password = builder["Password"];

Note that for an OLE DB connection string, only the standard cross-provider properties have strongly-typed property names, all the rest are accessed via the indexer.

Christian Hayter