5

I would like to modify the value of the "data source" component in a connection string. I'm thinking of the following solution:

Using this regex pattern:

"data source\=((\w|\-)+?\\{1}\w+?)\;"

I can obtain the following string matches:

Match.Groups[0].Value = "data source=MY-PC\SQLEXPRESS;"
Match.Groups[1].Value = "MY-PC\SQLEXPRES"

So in the connection string firstly I would like to find the part matching with the "data source=something;", and secondly replace just the "something" in the connection string. How to do that?

4 Answers 4

11

If you insist Regex replacing, please note C# cannot modify a built string, you need to get a new string with the needed part replaced.

var connectionString = @"data source=MY-PC\SQLEXPRESS;";
var pattern = @"(data source=)((\w|\-)+?\\\w+?)\;";
var newConnectionString = Regex.Replace(connectionString, pattern, "$1" + "something");
Console.WriteLine(newConnectionString);
Sign up to request clarification or add additional context in comments.

1 Comment

That was the solution I was looking for and figured out myself in the meantime. With Regex.Replace I just replaced the matched part to a created string that I created previously with String.Format("data source={0};", newSql);
1

For most connection string types in .NET there should be a corresponding ConnectionStringBuilder class to handle this sort of thing. How are you connecting to your DB?

1 Comment

With EntityFramework. There is a connection string in the app.config. Thanks anyway, but the question is more to the Regex usage, not specifically to connectionstring-handling.
0

Just replace it.

string dbSource = "data source=myserver\\sqlexpress";

int sLen = dbSource.IndexOf("=") + 1;
string getString = dbSource.Substring(sLen, dbSource.Length - sLen);

dbSource = dbSource.Replace(getString, "whatyouwantotoreplaceitwith");

3 Comments

That wouldn't do the trick as the connectionstring contains more equality sign.
@Pistaatortenesz that doesn't matter, indexOf will only return the position of the first '=' sign. My solution will work 100% of the time in this case, regardless of how many equals signs are in the string.
"metadata=", "provider=", "connection string=", all these precedes the data source in my connection string. But I also would like to modify Password and User Id as well... so the order doesn't count anyway.
0

You can split your matches further by using simple string.split with '=' character or if you like regular expressions see MSDN Regex.Replace Method

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.