Separating a string by semicolons when considering escaped characters

Really simple problem:

I want to split the connection string into my keyword / value pairs, for example, the following connection string:

Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=vm-jp-dev2;Data Source=scsql\sql2005;Auto Translate=False

It would be:

Provider=SQLOLEDB.1
Integrated Security=SSPI
Persist Security Info=False
Initial Catalog=vm-jp-dev2
Data Source=scsql\sql2005
Auto Translate=False

The problem is that the MSDN documentation claims that connection string values ​​can contain semicolons if the value is enclosed in single or double quotation marks, (so if I understand this will be true):

Provider="Some;Provider";Initial Catalog='Some;Catalog';...

What is the best way to split this line (in C #)?

+3
source share
4 answers

There is a DBConnectionStringBuilder class that will do what you want ...

        System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();

        builder.ConnectionString = "Provider=\"Some;Provider\";Initial Catalog='Some;Catalog';";

        foreach (string key in builder.Keys)
        {
            Response.Write(String.Format("{0}: {1}<br>", key , builder[key]));
        }
+9

- . - :

public static IEnumerable<string> SplitString(string str)
{
    int StartIndex = 0;
    bool IsQuoted = false;
    for (int I = 0; I < str.Length; I++)
    {
        if (str[I] == '"')
            IsQuoted = !IsQuoted;
        if ((str[I] == ';') && !IsQuoted)
        {
            yield return str.Substring(StartIndex, I - StartIndex);        
            StartIndex = I + 1;
        }
    }

    if (StartIndex < str.Length)
        yield return str.Substring(StartIndex);
}
0

-. , . , .

- , regex.Split, :

var re = new Regex(@"([\w\s]+=\s*?(?:['""][\w\s]+['""]|[\w\s]+));");
var parts = re.Split(connectionString)

:

  • ( )
  • - ( [\ s\w] , ).

, , .

EDIT: . DbConnectionStringBuilder IEnumerable, :

using System;
using System.Collections.Generic;
using System.Data.Common;

class Program {
    static void Main(string[] args) {
        string conStr = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=vm-jp-dev2;Data Source='scsql\sql;2005';Auto Translate=False";

        var cb = new DbConnectionStringBuilder();
        cb.ConnectionString = conStr;
        int n = 0;
        foreach (KeyValuePair<string, object> c in cb) {
            Console.WriteLine("#{0}: {1}={2}", ++n, c.Key, c.Value);
        }
    }
}
0

SQL Server :

SqlConnectionStringBuilder decoder = new SqlConnectionStringBuilder(connectionString);

string UserID = decoder.UserID; 
string Password = decoder.Password; 

.

0

Source: https://habr.com/ru/post/1711808/


All Articles