C#正则表达式一般匹配

时间:2013-10-14 10:29:47

标签: c# regex match

我收到如下消息,我有2个正则表达式。

对于正则表达式rh,它运作良好。虽然对于正则表达式rh1,我无法弄明白,匹配应返回类似"{{0:0.00}%,{ABND,1000},/,{OFRD,1002}}"而不是"{0:0.00"的内容,这将替换为最终值。

我很感激任何建议。

T.Format = "T1 Message: {{0:0.00}%,{ABND,1000},/,{OFRD,1002}}";


Regex rh = new Regex(@"{{(.*?)}(.*?),{(.*?),(.*?)},(.*?),{(.*?),(.*?)}}");
Match mh = rh.Match(T.Format);
Regex rh1 = new Regex(@"{(.*?)}");
Match mh1 = rh1.Match(T.Format);
decimal decReturn = 0;
string h1 = mh.Groups[1].Value.ToString();
string h2 = mh.Groups[2].Value.ToString();
string h3 = mh.Groups[3].Value.ToString();
string h4 = mh.Groups[4].Value.ToString();
string h5 = mh.Groups[5].Value.ToString();
string h6 = mh.Groups[6].Value.ToString();
string h7 = mh.Groups[7].Value.ToString();

switch (h5)
{
   case "+": decReturn = 0; break;
   case "-": decReturn = 0; break;
   case "*": decReturn = 0; break;
   case "/": decReturn = Convert.toInt32(h7) > 0 ? Convert.toInt32(h4) / Convert.toInt32(h7) * 100 : 0 * 100;
                            break;
   default: throw new Exception("invalid logic");
}

string strReplace = mh1.Groups[1].Value.ToString();
string strReturn = string.Empty;
strReturn = Convert.ToString(decReturn);
strReturn = Convert.ToString(T.Format).Replace(strReplace, strReturn);

1 个答案:

答案 0 :(得分:0)

问题在于:

{(.*?)}
    ^
  This makes a lazy match, one character at time

取而代之的是:

{(.*)}