我会采取另一种策略。首先,拆分字符串的子组件
var components = formatSeats.Split(',');
这将为您提供一个字符串数组。这将更有效地解析小块字符串而不是大字符串。
然后,您可以使用 aRegex
来提取值或像这样的简单代码:
foreach(var component in components)
{
var parts = component.Trim("[]".ToCharArray()).Split(';');
}
var results = from component in components
let c = component.Trim("[]".ToCharArray())
.Split(';')
.Select(c=>int.Parse(c.SubString(2))
select new { l = c[0], f=c[1], r=c[2], p = c[3] };
这将产生一个匿名类型的枚举。
foreach(var x in results)
{
Console.WriteLine("{0} / {1} / {2} / {3}", x.l, x.f, x.r, x.p);
}
如果您实际上需要Tuple
简单地将代码更改为:
var results = from component in components
let c = component.Trim("[]".ToCharArray())
.Split(';')
.Select(c=>int.Parse(c.SubString(2))
select new Tuple<int,int,int,int>{ l = c[0], f=c[1], r=c[2], p = c[3] };
但是,我主张编写一个小结构来简化代码并提高其可读性。
public struct MyValue
{
private readonly int m_L;
public int L { get {return m_L; } }
private readonly int m_F;
public int F { get {return m_F; } }
private readonly int m_R;
public int R { get {return m_R; } }
private readonly int m_P;
public int P { get {return m_P; } }
public MyValue(int l, int f, int r, int p)
{
m_L = l;
m_F = f;
m_R = r;
m_P = p;
}
}
....
var results = from component in components
let c = component.Trim("[]".ToCharArray())
.Split(';')
.Select(c=>int.Parse(c.SubString(2))
select new MyValue(c[0],c[1],c[2],c[3]);
最后,如果字符串总是有这种形式,你可以避免使用正则表达式。