Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a matched group value with Regex

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?

like image 351
Mitulát báti Avatar asked Feb 12 '23 13:02

Mitulát báti


1 Answers

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);
like image 153
Paul Chen Avatar answered Feb 14 '23 02:02

Paul Chen