对我来说,不使用正则表达式感觉更干净。如果你稍微放宽你的要求,只尝试一个正则表达式..它将匹配结束引号和开始引号之间的文本。
也许您手动操作会得到更好的结果?
string[] extractBetweenQuotes(string str)
{
var list = new List<string>();
int firstQuote = 0;
firstQuote = str.IndexOf("\"");
while (firstQuote > -1)
{
int secondQuote = str.IndexOf("\"", firstQuote + 1);
if (secondQuote > -1)
{
list.Add(str.Substring(firstQuote + 1, secondQuote - (firstQuote + 1)));
firstQuote = str.IndexOf("\"", secondQuote + 1);
continue;
}
firstQuote = str.IndexOf("\"", firstQuote + 1);
}
return list.ToArray();
}
用法:
string str = "there is a child object with name \"Child 1\" under parent \"Parent 1\" in the tree";
string[] parts = extractBetweenQuotes(str); // Child 1 and Parent 1 (no quotes)