C# 正则表达式常规匹配
本文关键字:常规匹 正则表达式 | 更新日期: 2023-09-27 18:35:26
我有如下消息,我有 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);
这是问题所在:
{(.*?)}
^
This makes a lazy match, one character at time
改为替换为:
{(.*)}