日期:2014-05-17  浏览次数:20818 次

急!用正则表达式 匹配一串字符并取出字段
功能实现:一串字符:“result={A}&description={B}&faillist={C}”
除了{A}{B}{C}是变量 其他都是固定的。我现在 想要的是 匹配这串字符 并且将{A}{B}{C}取出来。能实现么?正则该怎么写。我是菜鸟 求指导!!!!
------最佳解决方案--------------------
result参数能保证一定有吗?如果能,用下面的,注意取结果时用了命名捕获组

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}";