gpt4 book ai didi

c# - 使用Regex匹配SQL连接字符串的部分

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:50 26 4
gpt4 key购买 nike

我写了一个正则表达式来匹配SQL连接字符串的部分。在第一个规范中,“初始目录”等被迫不包含特殊字符。所以我有

string strConn = "Data Source=VAIOE;Initial Catalog=SomeTextOnlyCatname;Integrated 
Security=True;Persist Security Info=True;MultipleActiveResultSets=True;Connect Timeout=0;";
Regex databaseNameRegex =
new Regex(@"(?i)\b(Initial\sCatalog|Database)\b\s?=\s?(\w+\s*)*;?");


现在,我需要匹配名称可能带有符号,标点符号等的部分。例如

string strConn = "Data Source=VAIOE;Initial Catalog=N3wC@t@l0gName*6Symbols;Integrated 
Security=True;Persist Security Info=True;MultipleActiveResultSets=True;Connect Timeout=0;";


我想返回 Initial Catalog=N3wC@t@l0gName*6Symbols的地方。

我试过了

Regex databaseNameRegex =
new Regex(@"(?i)\b(Initial\sCatalog|Database)\b\s?=\s?(\w+\p{P}*\p{M}*\p{Z}*\s*)*;?");


但这失败,因为连接字符串中存在分号。什么是最好的正则表达式来处理呢?

谢谢你的时间。

最佳答案

您可以使用SqlConnection为您解析连接字符串并避免使用RegEx吗?如果只需要数据库名称,则应该可以进行以下操作:

var conn = new SqlConnection(strConn);
Console.WriteLine(conn.Database);


编辑

Allon Guralnek提供了一种更好的方法,谢谢!

为此使用 SqlConnectionStringBuilder-它会提取您需要的任何信息。

var connBuilder = new SqlConnectionStringBuilder(strConn);
Console.WriteLine(connBuilder.InitialCatalog);

关于c# - 使用Regex匹配SQL连接字符串的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10299860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com