0

Есть строка вида "key"="value";"key1"="value1";"key2"="value2".

У нас имеется строка key, нужно найти, что содержится после первого "=" и до ";".

То есть, зная ключ, нужно отпарсить его значение.

5
  • Регулярные выражения, не?
    – Bastiane
    7 окт 2014 в 16:52
  • Регулярка тут лишняя имхо, ваш вариант со сплитом более удобен и прост. Хотя, конечно, зависит от размера строки.
    – Чад
    7 окт 2014 в 17:07
  • 1
    Если значения могут содержать символ =, то простым String.Split() не обойтись.
    – AlexeyM
    7 окт 2014 в 17:49
  • Почему? Split("\";\"").Split("\"=\"") :-)
    – Чад
    7 окт 2014 в 17:57
  • key.Split(";")[0].Split("=")[1]; ?
    – smackmychi
    7 окт 2014 в 18:56

2 ответа 2

8

Как-то так должно пойти:

var s = "\"key\"=\"value\";\"key1\"=\"value1\";\"key2\"=\"value2\"";
var dict = s.Split(';')
            .Select(part => part.Split('=')
                                .Select(token => token.Trim('"')))
            .ToDictionary(tokens => tokens.First(),
                          tokens => tokens.Skip(1).Single());
var res = dict["key"];

Если ваши ключи или значения могут содержать знаки равенства или игнорируемые пробелы, так просто распарсить не выйдет, придётся написать хотя бы токенизатор. Например, такой код справляется с более враждебным вводом:

class Program
{
    static void Main(string[] args)
    {
        var s = "\"key\"=\"value\";\"key=1\"=\"value=1\" ;" +
                " \"   key2\" =\"va\\\\\\\"lue2\"";
        var dict = new SimpleTokenizer(s)
                        .GetTokens()
                        .SplitByToken(";")
                        .Select(ParseTerm)
                        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        var res = dict["key"];
    }

    static KeyValuePair<string, string> ParseTerm(IEnumerable<string> term)
    {
        using (var it = term.GetEnumerator())
        {
            if (!it.MoveNext()) // no first token => error
                throw new ArgumentException("term format wrong");
            var key = it.Current; // key is first token
            if (!it.MoveNext() || it.Current != "=") // second token must be "="
                throw new ArgumentException("term format wrong");
            if (!it.MoveNext()) // no third token => error
                throw new ArgumentException("term format wrong");
            var value = it.Current; // value is third token
            if (it.MoveNext()) // trailing tokens => error
                throw new ArgumentException("term format wrong");
            return new KeyValuePair<string, string>(key, value);
        }
    }
}

class SimpleTokenizer
{
    string source;
    public SimpleTokenizer(string source) { this.source = source; }

    public IEnumerable<string> GetTokens()
    {
        StringBuilder quotedString = null;
        bool escapeMode = false;
        foreach (var c in source)
        {
            if (quotedString == null)
            {
                if (char.IsWhiteSpace(c)) // ignoring whitespace in normal mode
                    continue;
                if (c == '"') // starting quote mode
                    quotedString = new StringBuilder();
                else
                    yield return c.ToString();
            }
            else if (escapeMode)
            {
                if (c == '\\' || c == '"')
                    quotedString.Append(c);
                else
                    throw new ArgumentException("invalid escape: \\" + c);
                escapeMode = false;
            }
            else // pure quote mode
            {
                if (c == '"') // leaving quote mode
                {
                    yield return quotedString.ToString();
                    quotedString = null;
                }
                else if (c == '\\')
                {
                    escapeMode = true;
                }
                else
                {
                    quotedString.Append(c);
                }
            }
        }
        if (escapeMode)
            throw new ArgumentException(
                "unexpected input stream end after escape character");
        if (quotedString != null)
            throw new ArgumentException(
                "unexpected input stream end in quoted string");
    }
}

static class TokenUtils
{
    public static IEnumerable<IEnumerable<string>> SplitByToken(
        this IEnumerable<string> list, string token)
    {
        List<string> currentPart = new List<string>();
        foreach (var t in list)
        {
            if (t == token)
            {
                yield return currentPart;
                currentPart = new List<string>();
            }
            else
            {
                currentPart.Add(t);
            }
        }
        yield return currentPart;
    }
}
1

String.Split - метод (Char[])

http://msdn.microsoft.com/ru-ru/library/b873y76a(v=vs.110).aspx

1
  • Я просто давно шарп не практиковал, забыл уже, что к чему :)
    – Bastiane
    7 окт 2014 в 16:57

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.