-1

I try to convert a database connection string in the format

postgres://<user>:<password>@<host>:<port>/<database>

to C# connection string

Username=<user>;Password=<dummy>;Host=<host>;Port=<port>;Database=<database>

The following code demonstrates my attempt to dissect the connection string.

public static void Main(string[] args)
{
    const string SERVER_DB = "postgres://dummy:dummy123@127.0.0.1:4321/my_db";

    Regex templConString = new Regex(@"^<protocol>://<user>:<password>@<host>:<port>/<database>$");
    Match match = templConString.Match(Environment.GetEnvironmentVariable("SERVER_DB") ?? SERVER_DB);

    Console.WriteLine(match.Groups["protocol"].Value);
    Console.WriteLine(match.Groups["user"].Value);
    Console.WriteLine(match.Groups["password"].Value);
    Console.WriteLine(match.Groups["port"].Value);
    Console.WriteLine(match.Groups["database"].Value);

    Debugger.Break();
}

The resulting output however is empty. I cannot find a lot of helpful information online to this topic.

EDIT

Regex templConString = new Regex(@"^(?<protocol>\w+)://(?<user>\w+):(?<pass>\w+)@(?<host>[\.\w]+):(?<port>\w+)/(?<database>\w+)/*$");

Gave me what I was looking for

Benj
  • 889
  • 1
  • 14
  • 31
  • 5
    Forget about regex. Use `new Uri("postgres://dummy:dummy123@127.0.0.1:4321/my_db")`. Use its properties, like `Host`, `Port`, and `Segments.Last()`, and you'll have to parse the `UserInfo` property by splitting on `:`. – madreflection Aug 30 '19 at 17:36

1 Answers1

0

You don't want regex here (see comment by @madreflection) but if you did it should look like this:

@"^(?<protocol>\w+)://(?<user>\w+):(?<password>\w+)@(?<host>\w+):(?<port>\w+)/(?<database>\w+)$"

You create the group by using ( and )

Then you name it with ?<name>

There is actually documentation that explains this here

https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.8

I like your syntax better, but sadly that is not how regex works.

Hogan
  • 69,564
  • 10
  • 76
  • 117
  • Replacing the regular expression in the example above still results in an empty output – Benj Aug 30 '19 at 17:45
  • 1
    Then your input data is wrong @Benj? Can't say without debugging it. Use the obect info like madreflection suggests – Hogan Aug 30 '19 at 17:46