0

Lets say I have this SQL Server connection string in C#:

Driver={SQL Server};server=.\sqlexpress;uid=myid;pwd=password;

I would like to remove the Driver= portion of the string, no matter where it appears in the string. So that afterwards it looks like this:

server=.\sqlexpress;uid=myid;pwd=password;

I have been trying Regex for a while with no luck.

1
  • Could you put that regex you tried in your question? Commented Jan 19, 2014 at 14:13

5 Answers 5

2

You're looking for the OdbcConnectionStringBuilder class, which will parse this for you.

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

Comments

2

You can do it like this:

res = Regex.Replace(connStr, "Driver=[{][^}]*[}];", "");

For your string it produces

server=.\sqlexpress;uid=myid;pwd=password;

Demo on ideone.

Comments

1

You can use this:

string pattern = @"\bDriver=[^;]+;";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

5 Comments

@RoyiNamir: indeed, line breaks are included. Is it a problem?
Doh! I was making it too complex. Thanks!
This breaks if Driver is at the end of the string without the ; separator. server=.\sqlexpress;uid=myid;pwd=password;Driver={SQL Server}
@wdosanjos: in this specific case you can use (?:;|$) instead of ;
To be more waterproof, you can replace \b with (?<=^|[;\n])[^\S\n]*
0

Might not work as it stands but I hope you get the idea:

string result = string.Join(";", connectionString
    .Split(';')
    .Where(p => !p.StartsWith('Driver'))

As a side note, I find it amazing that there are four completely different solutions ;)

Comments

0

To expand on the answer SLaks gave:

[TestMethod]
public void TestMethod1()
{
    var connStr = "Driver={SQL Server};server=.\\sqlexpress;uid=myid;pwd=password;";
    var builder = new DbConnectionStringBuilder();
    builder.ConnectionString = connStr;
    builder.Remove("Driver");
    connStr = builder.ConnectionString;
    Assert.AreEqual("server=.\\sqlexpress;uid=myid;pwd=password", connStr);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.