在String中用括号中的表达式求值

时间:2016-04-06 21:07:54

标签: java string parsing replace

在Java中,如果我有一个像import sqlite3 import subprocess conn = sqlite3.connect('stockage.db') cursor = conn.cursor() filename = '../Collecteur/collecteur_cpu_reseau.txt' proc_name = subprocess.check_output(["sed","-n",r"1p",filename]) proc_freq = subprocess.check_output(["sed","-n",r"2p",filename]) proc_core = subprocess.check_output(["sed","-n",r"3p",filename]) proc_hyperthreading = subprocess.check_output(["sed","-n",r"4p",filename]) proc_architecture = subprocess.check_output(["sed","-n",r"5p",filename]) proc_cache_L1 = subprocess.check_output(["sed","-n",r"6p",filename]) proc_cache_L2 = subprocess.check_output(["sed","-n",r"7p",filename]) proc_cache_L3 = subprocess.check_output(["sed","-n",r"8p",filename]) proc_virtualisation = subprocess.check_output(["sed","-n",r"9p",filename]) proc_load_average = subprocess.check_output(["sed","-n",r"10p",filename]) ip_infos_addr_ipv4 = subprocess.check_output(["sed","-n",r"11p",filename]) ip_infos_addr_ipv6 = subprocess.check_output(["sed","-n",r"12p",filename]) ip_publique_addr = subprocess.check_output(["sed","-n",r"13p",filename]) carte_reseau = subprocess.check_output(["sed","-n",r"14p",filename]) cursor.execute(""" INSERT INTO sonde_cpu_reseau(proc_name,proc_freq,proc_core,proc_hyperthreading,proc_architecture,proc_cache_L1,proc_cache_L2,proc_cache_L3,proc_virtualisation,proc_load_average, ip_infos_addr_ipv4,ip_infos_addr_ipv6,ip_publique_addr,carte_reseau) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",(proc_name,proc_freq,proc_core,proc_hyperthreading,proc_architecture,proc_cache_L1,proc_cache_L2,proc_cache_L3,proc_virtualisation,proc_load_average, ip_infos_addr_ipv4,ip_infos_addr_ipv6,ip_publique_addr,carte_reseau)) conn.commit() 这样的字符串,我怎么能用括号替换括号中的所有表达式来获取字符串"(3+5)x + x^(6/2)"

1 个答案:

答案 0 :(得分:1)

这取决于你想要做什么。对于更复杂的情况,您可以/应该使用像ANTLR这样的解析器生成器。如果表达式不比你的例子(简单的算术)复杂,你可以尝试用JavaScript / Nashorn分析表达式。

使用Use the backreference in a regex to replace a text dynamically解决方案:

public static void main(String[] args) throws ScriptException {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    String x = "(3+5)x + x^(6/2)";

    // can also be extended to expressions like 3+5*5 with 
    // Pattern.compile("\\(\\d+([+/*-]\\d+)+\\)")
    Pattern simpleArithmeticExpr = Pattern.compile("\\(\\d+[+/]\\d+\\)"); 
    Matcher matcher = simpleArithmeticExpr.matcher(x);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String expr = matcher.group();
        String evaluatedExpr = String.valueOf(engine.eval(expr));
        matcher.appendReplacement(sb, evaluatedExpr );
    }
    matcher.appendTail(sb);
    System.out.println(sb); // 8x + x^3

}

如果Javascript解决方案是慢速/重量级,你也可以自己解析它。