這種方式的基本思想就是迴圈使用正規表示式找出字串中不帶括號的那一部分,再分析出各個數字和運算子以及函式,並執行運算,然後將結果替換原表示式中相應部分,直到最後不能再進行任何替換。如:
(3+5)*sin(7+9) -----> (3+5)*sin(7+9) ----->8*sin(7+9) -----> 8*sin16----> 8*sin16 ------> 8*-0.2879 -----> -2.3
先定義幾個正規表示式:
static regex num = new regex(@"(\-?\d+\.?\d*)"); //匹配浮點數字
static regex power = new regex(num.tostring() + @"\^" + num.tostring());//匹配a^b形式的冪次運算
static regex addsub = new regex(num.tostring() + "([+-])" + num.tostring());//匹配加減運算
static regex muldiv = new regex(num.tostring() + "([*/])" + num.tostring());//匹配乘除運算
static regex innerregex = new regex(@"\([^\(\)]+\)");//匹配最底層的括號表示式
static regex functionregex = new regex(@"(ln|lg|sin|cos|tan|ctg|sh|ch|th|arcsin|arccos|arctan)" + num.tostring());//匹配各種數學函式
static regex lbrackets = new regex(@"\|\]");//匹配右括號
下面就是具體**了(沒有進行任何錯誤、異常檢查):
public static class function
|\]");
/// 計算表示式
/// 表示式
public static string eval(string expressions)
);//統一使用小括號
expressions = rbrackets.replace(expressions, (match match) => );
if (check(expressions)));}
while (innerregex.ismatch(expressions));
}return evalinner(expressions);
}/// 用於計算不含括號的表示式的值
/// 要計算的表示式
/// 計算結果
private static string evalinner(string expressions));}
while (power.ismatch(expressions)));}
while (muldiv.ismatch(expressions)));}
while (addsub.ismatch(expressions)));}
return expressions;
}/// 用於計算單變數函式表示式的值
/// 要計算的表示式
/// 計算結果
private static string evalsingle(string expressions));}
return expressions;
}private static string evalsingle(match match)
return result.tostring();
}/// 對表示式進行檢查,確保其格式符合要求
/// 表示式
/// 是否符合要求
public static bool check(string expressions)
/// 檢查括號是否匹配
/// 表示式
/// 是否匹配
private static bool checkbrackets(string expressions)
if (c == ')')
}return i == 0;
}}
正規表示式 表示式
網域名稱 a za z0 9 a za z0 9 a za z0 9 a za z0 9 interneturl a za z s 或 http w w w 手機號碼 13 0 9 14 5 7 15 0 1 2 3 5 6 7 8 9 18 0 1 2 3 5 6 7 8 9 d 號碼 x x x...
正規表示式 正規表示式 總結
非負整數 d 正整數 0 9 1 9 0 9 非正整數 d 0 負整數 0 9 1 9 0 9 整數 d 非負浮點數 d d 正浮點數 0 9 0 9 1 9 0 9 0 9 1 9 0 9 0 9 0 9 1 9 0 9 非正浮點數 d d 0 0 負浮點數 正浮點數正則式 英文本串 a za z...
EL表示式,正規表示式,
el表示式,正規表示式。正規表示式 又稱規則表示式 英語 regular expression,在 中常簡寫為regex regexp或re 電腦科學的乙個概念。正則表通常被用來檢索 替換那些符合某個模式 規則 的文字。e l expression language 目的 為了使jsp寫起來更加簡單...