Функция для извлечения все между фигурными скобками:
public string retrieve(string input)
{
var pattern = @"\{.*\}";
var regex = new Regex(pattern);
var match = regex.Match(input);
var content = string.Empty;
if (match.Success)
{
// remove start and end curly brace
content = match.Value.Substring(1, match.Value.Length - 2);
}
return content;
}
Затем с помощью функции извлечения содержимого:
var input = @"Data={Person, Id, Specification={Id, Destination={Country, Price}}}";
var content = retrieve(input);
Console.Out.WriteLine(content);
if (!string.IsNullOrEmpty(content))
{
var subcontent = retrieve(content);
Console.Out.WriteLine(subcontent);
// and so on...
}
Выход является:
Person, Id, Specification={Id, Destination={Country, Price}}
Id, Destination={Country, Price}
Вы не можете использовать string.Split (',') для извлечения Лицо и Id, потому что оно также разделило бы строки между скобками, и вы не захотите этого. Вместо того, чтобы использовать в качестве предложенной String.indexOf два раза от правильного положения, и вы будете правильно иметь подстроки:
// TODO error handling
public Dictionary<string, string> getValues(string input)
{
// take everything until =, so string.Split(',') can be used
var line = input.Substring(0, input.IndexOf('='));
var tokens = line.Split(',');
return new Dictionary<string, string> { { "Person" , tokens[0].Trim() }, { "Id", tokens[1].Trim() } };
}
Функция должна быть использована на извлеченном содержания:
var input = @"Data={Person, Id, Specification={Id, Destination={Country, Price}}}";
var content = retrieve(input);
var tokens = getValues(content);
Console.Out.WriteLine(string.Format("{0} // {1} // {2}", content, tokens["Person"], tokens["Id"]));
if (!string.IsNullOrEmpty(content))
{
var subcontent = retrieve(content);
Console.Out.WriteLine(subcontent);
var subtokens = getValues(subcontent);
Console.Out.WriteLine(string.Format("{0} // {1} // {2}", subcontent, subtokens["Person"], subtokens["Id"]));
}
И выход является:
Person, Id, Specification={Id, Destination={Country, Price}} // Person // Id
Id, Destination={Country, Price}
Id, Destination={Country, Price} // Id // Destination
Непохоже, данные JSON вообще, если возможно, вы имеете в виду, что она так же содержит фигурные скобки , Библиотека JSON здесь не поможет. –
Не существует ли способа получить первый индекс скобок и последний индекс внутри строки, а затем получить все данные между этими индексами? И сделать то же самое для любого другого кронштейна внутри скобки? –
Похоже, вам просто нужно снять первые шесть и последние персонажи ... это все, что вам нужно? –