[英]Match Sections of SQL Connection String with Regex
我写了一个正则表达式来匹配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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.