有probabl這是一個正則表達式的解決方案,但如果格式嚴格,我首先嚐試高效的字符串方法。以下內容適用於您的輸入。
我使用的是自定義類,TeamGroup
,封裝複雜性和一個對象來保存所有相關屬性:
public class TeamGroup
{
public string Group { get; set; }
public string[] Teams { get; set; }
public static TeamGroup ParseOut(string fullString)
{
TeamGroup tg = new TeamGroup{ Teams = new string[]{ } };
int index = fullString.IndexOf("group = '");
if (index >= 0)
{
index += "group = '".Length;
int endIndex = fullString.IndexOf("'", index);
if (endIndex >= 0)
{
tg.Group = fullString.Substring(index, endIndex - index).Trim(' ', '\'');
endIndex += 1;
index = fullString.IndexOf(" and (team in (", endIndex);
if (index >= 0)
{
index += " and (team in (".Length;
endIndex = fullString.IndexOf(")", index);
if (endIndex >= 0)
{
string allTeamsString = fullString.Substring(index, endIndex - index);
tg.Teams = allTeamsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Trim(' ', '\''))
.ToArray();
}
}
}
}
return tg;
}
}
你會使用它這樣:
string fullString = "group = '2843360' and (team in ('TEAM1', 'TEAM2','TEAM3'))";
TeamGroup tg = TeamGroup.ParseOut(fullString);
Console.Write("Group: {0} Teams: {1}", tg.Group, string.Join(", ", tg.Teams));
輸出:
Group: 2843360 Teams: TEAM1, TEAM2, TEAM3
如果您沒有看到其他解決方案,則很難提供更好的解決方案 –
爲什麼不發佈當前的解決方案,我們可以看到有關改進方案。 – tofutim
「並非總是像上面那樣3」 – tofutim