有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