【问题标题】:C# Regex General MatchingC# 正则表达式通用匹配
【发布时间】:2013-10-14 10:29:47
【问题描述】:

我有如下消息,我有 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);

【问题讨论】:

  • 您必须完善您的问题。该代码没有说明您要实现的目标。您能否向我们提供预期的输入以及该输入的预期输出?
  • 无论如何;这是作业吗?

标签: c# regex match


【解决方案1】:

问题来了:

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

改为:

{(.*)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2016-01-15
    相关资源
    最近更新 更多