Heroius / ExpressionStatic.cs

一次性的简单数学表达式解析,该代码实现了少量算符的识别和优先级的计算,适合初学者在文本表达式解析问题时用作参考。 若想了解更加丰富的内容,如可复用的解析过程,变量支持,通用算符支持,可拓展性,文本计算等,请发送电子邮件与我联系:heroius@163.com。 欢迎朋友们的批评建议! P.S.该代码曾用于叨叨小算盘v1.0

  表达式解析 最后更新时间 2013-11-19 14:58:33
ExpressionStatic.cs 397行 C#
Raw
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IEPI.Expression.Numeric
{
/// <summary>
/// 提供单次分析表达式并计算结果的方法,表达式应遵循如下格式:
/// <para>使用半角字符,只识别英文字符和少数符号;</para>
/// <para>不支持变量代数;</para>
/// <para>一些特殊的表达式规范,如“%”表示的是求余计算;</para>
/// <para>单目运算(函数)的参数要写在“[ ]”内,嵌套使用时以“()”分开;</para>
/// <para>单目算符仅支持EXP,ABS,SIN,COS,TAN,LOG。</para>
/// </summary>
public static class ExpressionStatic
{
#region 判断器

//判断当前字符是否为操作数的一部分
static bool IsNumber(char dgt)
{
if (dgt == '0' || dgt == '1' || dgt == '2' || dgt == '3' || dgt == '4' || dgt == '5' || dgt == '6' ||
dgt == '7' || dgt == '8' || dgt == '9' || dgt == '.' || dgt == '-')
return true;
else
return false;
}
//判断当前字符是否为二元操作符的一部分
static bool IsBinaryOperator(char dgt)
{
if (dgt == '+' || dgt == '-' || dgt == '*' || dgt == '/' || dgt == '^')
return true;
else
return false;
}

#endregion

#region 单目运算

//单目计算
static double UnaryCalculation(double Operand, string FuncName)
{
switch (FuncName)
{
case "EXP":
return Math.Exp(Operand);
case "ABS":
return Math.Abs(Operand);
case "SIN":
return Math.Sin(Operand);
case "COS":
return Math.Cos(Operand);
case "TAN":
return Math.Tan(Operand);
case "LOG":
return Math.Log(Operand);
default:
//异常
return 0;
}
}
//构建单目运算
static string UnaryOperator(string Expression)
{
//单目算符格式Func[Xprs]
//一次计算
bool IsCaught = false;
int left = 0, right = Expression.Length - 1;
for (int i = 0; i < Expression.Length; i++)
{
//对于表达式的每一位,首先找到'['
if (!IsCaught)
{
if (Expression[i] == '[')
{
left = i + 1;
IsCaught = true;
}
}
//再找到']'
else
{
if (Expression[i] == ']')
{
right = i - 1;
break;
}
}
}
//捕捉:剥离回调
if (IsCaught)
{
int pr = 0;
//截取单目算符,判断算符种类
//找到左边界
for (int i = left - 1; i >= 0; i--)
{
if (IsBinaryOperator(Expression[i]))
{
pr = i + 1;
break;
}
}
string
PreXprs = Expression.Remove(pr),
LatXprs = Expression.Remove(0, right + 2),
SubXprs = Expression.Substring(left, right - left + 1),
FuncName = Expression.Substring(pr, left - pr - 1);
double SubRslt = Convert.ToDouble(Sequencial(SubXprs));
Expression = PreXprs + UnaryCalculation(SubRslt, FuncName).ToString() + LatXprs;
return UnaryOperator(Expression);
}
//未捕捉:返回
else
{
return Expression;
}
}

#endregion

#region 双目运算

//进行双目运算,如加减乘除和乘方开方
static double BinaryCalculation(double Prenum, double Nextnum, char Opt)
{
switch (Opt)
{
case '^':
return Math.Pow(Prenum, Nextnum);
case '+':
return Prenum + Nextnum;
case '-':
return Prenum - Nextnum;
case '*':
return Prenum * Nextnum;
case '/':
return Prenum / Nextnum;
case '%':
return Prenum % Nextnum;
default:
return 0;
}
}
//构建双目运算
static string BinaryOperator(string Expression, char Opt)
{
int lenght = Expression.Length;
bool IsCaught = false;
for (int i = 0; i < lenght; i++)
{
if (Expression[i] == Opt)
{
double Prenum = 0, Nextnum = 0;
int left = 0, right = lenght - 1;
IsCaught = true;
//进行一次计算
//取前一个操作数
for (int f = i - 1; f >= 0; f--)
{
if (!IsNumber(Expression[f]) || f == 0)
{
if (f == 0)
f--;
Prenum = Convert.ToDouble(Expression.Substring(f + 1, i - f - 1));
left = f + 1;
break;
}
}
//取后一个操作数
for (int l = i + 1; l < lenght; l++)
{
if (!IsNumber(Expression[l]) || l == lenght - 1)
{
if (l == lenght - 1)
l++;
Nextnum = Convert.ToDouble(Expression.Substring(i + 1, l - i - 1));
right = l - 1;
break;
}
}
//更新字符串
string
ForXprs = Expression.Remove(left),
SubXprs = BinaryCalculation(Prenum, Nextnum, Opt).ToString(),
LatXprs = Expression.Remove(0, right + 1);
Expression = ForXprs + Bracketed(SubXprs) + LatXprs;
break;
}
}
//假如式中含有目标算符,则进行下一轮检验
if (IsCaught) return BinaryOperator(Expression, Opt);
//假如式中没有目标算符,则直接返回
else return Expression;
}
//构建双目运算
static string BinaryOperator(string Expression, char Opt1, char Opt2)
{
int lenght = Expression.Length;
bool IsCaught = false;
for (int i = 0; i < lenght; i++)
{
char Opt = Expression[i];
if (Opt == Opt1 || Opt == Opt2)
{
double Prenum = 0, Nextnum = 0;
int left = 0, right = lenght - 1;
IsCaught = true;
//进行一次计算
//取前一个操作数
for (int f = i - 1; f >= 0; f--)
{
if (!IsNumber(Expression[f]) || f == 0)
{
if (f == 0)
f--;
Prenum = Convert.ToDouble(Expression.Substring(f + 1, i - f - 1));
left = f + 1;
break;
}
}
//取后一个操作数
for (int l = i + 1; l < lenght; l++)
{
if (!IsNumber(Expression[l]) || l == lenght - 1)
{
if (l == lenght - 1)
l++;
Nextnum = Convert.ToDouble(Expression.Substring(i + 1, l - i - 1));
right = l - 1;
break;
}
}
//更新字符串
string
ForXprs = Expression.Remove(left),
SubXprs = BinaryCalculation(Prenum, Nextnum, Opt).ToString(),
LatXprs = Expression.Remove(0, right + 1);
Expression = ForXprs + Bracketed(SubXprs) + LatXprs;
break;
}
}
//假如式中含有目标算符,则进行下一轮检验
if (IsCaught) return BinaryOperator(Expression, Opt1, Opt2);
//假如式中没有目标算符,则直接返回
else return Expression;
}
//构建双目运算
static string BinaryOperator(string Expression, char Opt1, char Opt2, char Opt3)
{
int lenght = Expression.Length;
bool IsCaught = false;
for (int i = 0; i < lenght; i++)
{
char Opt = Expression[i];
if (Opt == Opt1 || Opt == Opt2 || Opt == Opt3)
{
double Prenum = 0, Nextnum = 0;
int left = 0, right = lenght - 1;
IsCaught = true;
//进行一次计算
//取前一个操作数
for (int f = i - 1; f >= 0; f--)
{
if (!IsNumber(Expression[f]) || f == 0)
{
if (f == 0)
f--;
Prenum = Convert.ToDouble(Expression.Substring(f + 1, i - f - 1));
left = f + 1;
break;
}
}
//取后一个操作数
for (int l = i + 1; l < lenght; l++)
{
if (!IsNumber(Expression[l]) || l == lenght - 1)
{
if (l == lenght - 1)
l++;
Nextnum = Convert.ToDouble(Expression.Substring(i + 1, l - i - 1));
right = l - 1;
break;
}
}
//更新字符串
string
ForXprs = Expression.Remove(left),
SubXprs = BinaryCalculation(Prenum, Nextnum, Opt).ToString(),
LatXprs = Expression.Remove(0, right + 1);
Expression = ForXprs + Bracketed(SubXprs) + LatXprs;
break;
}
}
//假如式中含有目标算符,则进行下一轮检验
if (IsCaught) return BinaryOperator(Expression, Opt1, Opt2, Opt3);
//假如式中没有目标算符,则直接返回
else return Expression;
}

#endregion

#region 算式解析

//分析顺序表达式
/// <summary>
/// 得到顺序算式的字符串型结果
/// </summary>
/// <param name="Expression">需要计算的原始数值算式</param>
/// <returns>字符串型结果</returns>
static string Sequencial(string Expression)
{
#region 减号处理
for (int i = 0; i < Expression.Length; i++)
{
char last = 'x';
if (i != 0)
last = Expression[i - 1];
if (Expression[i] == '+')
{
if (i == 0 || last == '(' || last == '[')
Expression = Expression.Remove(i);
}
else if (Expression[i] == '-')
{
if (IsNumber(last) || last == ')' || last == ']')
Expression = Expression.Insert(i, "+");
i++;
}
}
#endregion

//捕获函数及单目算符,如sin[]、Abs[]
Expression = UnaryOperator(Expression);
//捕获乘方运算
Expression = BinaryOperator(Expression, '^');
//捕获乘除运算
Expression = BinaryOperator(Expression, '*', '/', '%');
//捕获加减运算
Expression = BinaryOperator(Expression, '+');
return Expression;
}
//逐层剥离括号
/// <summary>
/// 得到任意数值算式的字符串型结果
/// </summary>
/// <param name="Expression">需要计算的原始数值算式</param>
/// <returns>字符串型结果</returns>
static string Bracketed(string Expression)
{
int length = Expression.Length, left = 0, right = length - 1;
bool IsBracketed = false;
for (int i = 0; i < length; i++)
{
if (Expression[i] == '(')
{
left = i;
IsBracketed = true;
}
if (Expression[i] == ')')
{
right = i;
break;
}
}
if (IsBracketed)
{
string
ForXprs = Expression.Remove(left),
SubXprs = Expression.Substring(left + 1, right - left - 1),
LatXprs = Expression.Remove(0, right + 1),
NewXprs = ForXprs + Bracketed(SubXprs) + LatXprs;
return Bracketed(NewXprs);
}
else
return Sequencial(Expression);
}
//预整理
/// <summary>
/// 得到任意数值算式的double型结果
/// </summary>
/// <param name="Expression">需要计算的原始数值算式</param>
/// <returns>双精度型结果</returns>
public static double NumericExpression(string Expression)
{
//除去空格
Expression = Expression.Replace(" ", "");
//符号修正

return Convert.ToDouble(Bracketed(Expression));
}

#endregion
}
}