1

我正在尝试从如下所示的 XML 文件中提取数据库连接字符串:

<DTS:Property DTS:Name="ConnectionString">
    Data Source=Instance1;
    User ID=;
    Initial Catalog=DB;
    Provider=SQLOLEDB.1;
    Integrated Security=SSPI;
    Auto Translate=False;    
</DTS:Property>
</DTS:ConnectionManager>
    </DTS:ObjectData>
</DTS:ConnectionManager>
<snip>

现在理想情况下,我希望有一个团体回来

[0] = 数据源=Instance_1;用户 ID=;初始目录=DB1;提供者=SQLOLEDB.1;集成安全性=SSPI;自动翻译=False;

[1] = DB1

所以我有这个正则表达式:

<DTS:Property DTS:Name="ConnectionString">(?<cs>.*)(?<cs>)</DTS:Property>

所以我在第一个()中捕获了值,有没有办法可以做一个正则表达式来捕获完整的连接字符串和只有数据库?

4

1 回答 1

1

当然。用正则表达式给猫剥皮的方法有很多。见下文。

我推荐连接字符串生成器


为了娱乐和教育,这里是这个问题的正则表达式解决方案:

注意我故意展示如何用正则表达式处理连接字符串,因为 XML 应该用 XmlReader、XDocument、XPathReader 或 XmlDocument(等)处理。

在http://ideone.com/I47R8上现场观看

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

public class Program
{
    const string kvPair   = @"(?<pair>(?<key>.*?)\s*=\s*(?<value>.*?))";
    const string kvpRegex = "^" + kvPair + "$";
    const string csRegex  = @"^\s*(?<cs>(?:" + kvPair + @"\s*(;\s*|\s*$))+)$";

    public static void Main(string[] args)
    {
        const string input = @"Data Source=Instance1;User ID=;Initial Catalog=DB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Auto Translate=False;";

        var match = Regex.Match(input, csRegex);
        Console.WriteLine("======\nSuccess: {0}\n======", match.Success);

        // 'smart' dictionary from the subcaptures:
        var dict = match.Groups["pair"]
            .Captures
            .Cast<Capture>()
            .Select(cap => Regex.Match(cap.Value, kvpRegex))
            .ToDictionary(submatch => submatch.Groups["key"].Value,
                          submatch => submatch.Groups["value"].Value);

        foreach (var kvp in dict)
            Console.WriteLine(kvp);

        // Getting just the DB1:
        Console.WriteLine("======\nCatalog: {0}\n======", dict["Initial Catalog"]);

        // raw access from csRegex full match:
        foreach (Capture cap in match.Groups["key"].Captures)
            Console.WriteLine("Key: '{0}'", cap.Value);
        foreach (Capture cap in match.Groups["value"].Captures)
            Console.WriteLine("Value: '{0}'", cap.Value);

        Console.WriteLine("======\nConnection string: '{0}'", match.Groups["cs"].Value);
    }
}

使用正确的输出:

======
Success: True
======
[Data Source, Instance1]
[User ID, ]
[Initial Catalog, DB]
[Provider, SQLOLEDB.1]
[Integrated Security, SSPI]
[Auto Translate, False]
======
Catalog: DB
======
Key: 'Data Source'
Key: 'User ID'
Key: 'Initial Catalog'
Key: 'Provider'
Key: 'Integrated Security'
Key: 'Auto Translate'
Value: 'Instance1'
Value: ''
Value: 'DB'
Value: 'SQLOLEDB.1'
Value: 'SSPI'
Value: 'False'
======
Connection string: 'Data Source=Instance1;User ID=;Initial Catalog=DB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Auto Translate=False;'
于 2012-10-11T22:13:10.370 回答