日期:2014-05-18  浏览次数:21221 次

求一个正则表达式,匹配数组。
var pro = new Arrary(
0,
1,
2,
3(a s),
4,
5
);

var prox = new Arrary(
x,
1,
2,
3(a s),
4
);
类似这样,我只想匹配出来 pro 后面的 数组: 0,1,2,3.。,4,5 这样
不需要匹配到 下面一个prox的东西。。。
怎么写正则表达式???

------解决方案--------------------
C# code

void Main()
{
string str=@"var pro = new Arrary(
0,
1,
2,
3(a s),
4,
5
);

var prox = new Arrary(
x,
1,
2,
3(a s),
4
);
";
    Regex reg=new Regex(@"var\spro\s=\snew Arrary\(((?<o>\()|(?<-o>)\)|[^()]+)*(?(o)(?!))\);");
    foreach(Capture c in reg.Match(str).Groups[1].Captures)
    {
       Console.Write(Regex.Replace(c.Value.Trim(),"[\\D]+"," "));
    }
   /*
    0 1 2 3  4 5
   */
}

------解决方案--------------------
C# code
string str=@"var pro = new Arrary(
0,
1,
2,
3(a s),
4,
5
);

var prox = new Arrary(
x,
1,
2,
3(a s),
4
);
";
    Regex reg=new Regex(@"pro\s.+?Arrary\(([\s\S]+?)\);");
    foreach(Capture c in reg.Match(str).Groups[1].Captures)
    {
       Console.Write(Regex.Replace(c.Value.Trim(),"[\\D]+"," "));
    }

------解决方案--------------------
C# code
               string str = @"var pro = new Arrary(
0,
1,
2,
3(a s),
4,
5
);

var prox = new Arrary(
x,
1,
2,
3(a s),
4
);
";
                Regex reg = new Regex(@"(?<=var\spro\s=\snew Arrary\(\s*?((?!\);\s+)[\s\S])*?)[^,\r\n]+(?=,|\s*?\))");

                var result = reg.Matches(str).Cast<Match>().Select((a, index) => new { index=index,value=a.Value});
                /*
                 * +        [0]    { index = 0, value = "0" }    <Anonymous Type>
                    +        [1]    { index = 1, value = "1" }    <Anonymous Type>
                    +        [2]    { index = 2, value = "2" }    <Anonymous Type>
                    +        [3]    { index = 3, value = "3(a s)" }    <Anonymous Type>
                    +        [4]    { index = 4, value = "4" }    <Anonymous Type>
                    +        [5]    { index = 5, value = "5" }    <Anonymous Type>

                 */