C# 如何使用正则表达式转换数据库连接字符串格式?

C# 如何使用正则表达式转换数据库连接字符串格式?,c#,regex,match,C#,Regex,Match,我尝试将数据库连接字符串转换为 postgres://:@:// 到C#连接字符串 Username=;密码=;主机=;端口=;数据库= 下面的代码演示了我解析连接字符串的尝试 public static void Main(string[] args) { const string SERVER_DB = "postgres://dummy:dummy123@127.0.0.1:4321/my_db"; Regex templConString = new Regex(@"^

我尝试将数据库连接字符串转换为

postgres://:@://

到C#连接字符串

Username=;密码=;主机=;端口=;数据库=

下面的代码演示了我解析连接字符串的尝试

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();
}

publicstaticvoidmain(字符串[]args)
{
const string SERVER_DB=”postgres://dummy:dummy123@127.0.0.1:4321/my_db“;
正则表达式templConString=新正则表达式(@“^://:@://$”;
Match Match=templancontring.Match(Environment.GetEnvironmentVariable(“SERVER\u DB”)??SERVER\u DB);
Console.WriteLine(match.Groups[“protocol”].Value);
Console.WriteLine(match.Groups[“user”].Value);
Console.WriteLine(match.Groups[“password”].Value);
Console.WriteLine(匹配.Groups[“端口”].Value);
Console.WriteLine(match.Groups[“数据库”].Value);
Debugger.Break();
}
但是,结果输出为空。我在网上找不到很多关于这个话题的有用信息

编辑

Regex templConString = new Regex(@"^(?<protocol>\w+)://(?<user>\w+):(?<pass>\w+)@(?<host>[\.\w]+):(?<port>\w+)/(?<database>\w+)/*$");
Regex templeconstring=newregex(@“^(?\w+):/(?\w+):(?\w+):(?\w+/*$”;
给了我我想要的

你不想在这里使用正则表达式(见@madreflection的评论),但如果你这样做了,它应该是这样的:

@"^(?<protocol>\w+)://(?<user>\w+):(?<password>\w+)@(?<host>\w+):(?<port>\w+)/(?<database>\w+)$"
@“^(?\w+):/(?\w+):(?\w+)@(?\w+):(?\w+)/(?\w+)”
您可以使用

然后用

实际上,这里有文档说明了这一点


我更喜欢您的语法,但遗憾的是,regex不是这样工作的。

忘记regex吧。使用
新Uri(“postgres://dummy:dummy123@127.0.0.1:4321/my_db”)
。使用它的属性,如
Host
Port
Segments.Last()
,您必须通过在
上拆分来解析
UserInfo
属性。如果输入数据错误,替换上面示例中的正则表达式仍然会导致空输出@Benj?不能不调试它就说。像madreflection建议的那样使用OBCT信息