Вот быстрое и грязное решение, использующее Regex.Он также обрабатывает случай, когда есть текст перед первым {
и / или после последнего ]
.
Сначала Regex и строка для анализа:
//Regex: get things that start with a {, followed by one or more non-} characters, followed by a }
private const string Pattern = @"(\{[^\}]+\})";
private const string TheText = "{Lorem ipsum dolor} sit amet, consectetur adipiscing elit, Ut enim adminim veniam, quis {nostrud exercitation}";
Затем некоторыекод:
var regex = new Regex(Pattern);
var matches = regex.Matches(TheText);
var results = new List<string>();
var currentIndex = 0;
foreach (var match in matches.Cast<Match>())
{
var lastIndex = currentIndex;
//pickup any undelimited text at the beginning or between delimited groups
if (match.Index != currentIndex)
{
var unDelimited = TheText.Substring(currentIndex, match.Index - lastIndex);
results.Add(unDelimited);
currentIndex += unDelimited.Length;
}
results.Add(match.Groups[0].ToString());
currentIndex += match.Length;
}
//finally pickup any undelimited text at the end
if (TheText.Length > currentIndex)
{
results.Add(TheText.Substring(currentIndex));
}
Он использует регулярные выражения для поиска каждого из {some text here}
совпадений.Затем он просматривает эти совпадения, создавая список либо непосредственно из совпадения, либо из подстрок исходной строки (используя информацию о положении совпадений).
Я также проверил его с помощью строки:
private const string TheText = "before {first} middle {second} after";
Наконец, мой код сохраняет любые начальные или конечные пробелы в неограниченном тексте.Вы можете избавиться от них с помощью string.Trim