string test = "result=1&description=返回出错&faillist=13656645185,14587485478"; Regex reg = new Regex(@"(?i)result=(?<result>[^&]*)(?:&description=(?<description>[^&]*))?(?:&faillist=(?<faillist>[^&=]*))?"); Match m = reg.Match(test); if (m.Success) { richTextBox2.Text += "result:" + m.Groups["result"].Value + "\n"; richTextBox2.Text += "description:" + m.Groups["description"].Value + "\n"; richTextBox2.Text += "faillist:" + m.Groups["faillist"].Value + "\n"; }
[其他解释] 想带括号就把 Regex reg_imgformorA = new Regex( "[\\w\\W]*?result={([\\w\\W]*?)}"); 改成 Regex reg_imgformorA = new Regex( "[\\w\\W]*?result=([\\w\\W]*?)&"); [其他解释] (?i)result=\{([^{}]*?)\}&description=\{([^{}]*?)\}&faillist=\{([^{}]*?)\}
string str = "result={A}&description={B}&faillist={C}"; MatchCollection ary = Regex.Matches(str, @"(?i)result=\{([^{}]*?)\}&description=\{([^{}]*?)\}&faillist=\{([^{}]*?)\}"); foreach (Match m in ary) { Console.WriteLine(m.Value); Console.WriteLine(m.Groups[1].Value); Console.WriteLine(m.Groups[2].Value); Console.WriteLine(m.Groups[3].Value); }
[其他解释]
string str = "result=1&description=返回出错&faillist=13656645185,14587485478"; var ary = Regex.Matches(str, @"(\w*?)=([^$&\s]+)").Cast<Match>().Select(t => new { a = t.Groups[1].Value, value = t.Groups[2].Value }).ToArray(); foreach (var t in ary) { Console.WriteLine(t.a + ":" + t.value); } [其他解释] result=([^$&\s]+)[$&\s]description=([^$&\s]+)[$&\s]faillist=([^$&\s]+) [其他解释] string stra = "result={A}&description={B}&faillist={C}";
Regex reg_imgformorA = new Regex( "[\\w\\W]*?result={([\\w\\W]*?)}"); MatchCollection mcpiformorlist = reg_imgformorA.Matches(stra); if (mcpiformorlist.Count > 0) { string resulta = mcpiformorlist[0].Groups[1].Value; } Regex reg_imgformorB = new Regex( "[\\w\\W]*?&description={([\\w\\W]*?)}"); MatchCollection mcpiformorB = reg_imgformorB.Matches(stra); if (mcpiformorB.Count > 0) { string resultb = mcpiformorB[0].Groups[1].Value; } Regex reg_imgformorC = new Regex( "[\\w\\W]*?&faillist={([\\w\\W]*?)}"); MatchCollection mcpiformorC = reg_imgformorC.Matches(stra); if (mcpiformorC.Count > 0) { string resultb = mcpiformorC[0].Groups[1].Value; }
最后这个resulta 。 resultb.resultc输出的是A B C [其他解释] string str = "result={A}&description={B}&faillist={C}"; var ary = Regex.Matches(str, @"(\w*?)=([^$&\s]+)").Cast<Match>().Select(t => new { a = t.Groups[1].Value, value = t.Groups[2].Value }).ToArray(); foreach (var t in ary) { MessageBox.Show(t.a + ":" + t.value); } [其他解释]