Possible Duplicate:
Regular Expression to find a string included between two characters, while EXCLUDING the delimiters
我正在使用外部库“beanshell”的一种名为 Interpreter.eval() 的方法,该方法允许使用字符串进行数学运算并返回解决方案。
它工作正常,但如果我想求二次方或从中得到平方根,我必须修改原始字符串,就像
字符串 st ="x = 2+4*a*(b+c)^2"
我需要获取括号之间的字符,以将 "(b+c)^2" 替换为 "(b+c)*(b+c)"或“Math.pow((b+c),2)”
我该怎么做? 提前致谢!
----编辑----
终于找到解决办法了。
Interpreter interpreter = new Interpreter();
String st = "x = 2+4*1*(2*(1+1)^2)^2 + (4+5)^2";
int index = -2;
char prev;
char post;
int openPar = -1;
if (st.contains("^")) {
index = st.indexOf("^");
while (index != -1) {
prev = st.charAt(index - 1);
post = st.charAt(index + 1);
if (prev == ')') {
int match = 0;
int i = index - 2;
char check = '0';
boolean contiunar = true;
while (contiunar) {
check = st.charAt(i);
if (check == ')')
match++;
if (check == '(') {
if (match == 0) {
openPar = i;
contiunar = false;
} else
match = match - 1;
}
i = i - 1;
}
String rep = st.substring(openPar + 1, index - 1);
String resultado = "";
try {
interpreter.eval("r= Math.pow(" + rep + "," + post
+ ")");
resultado = interpreter.get("r").toString();
} catch (EvalError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
st = st.replace("(" + rep + ")^" + post, resultado);
} else {
st = st.replace(prev + "^" + post, prev + "*" + prev);
}
index = st.indexOf("^");
}
}
这样我修改了原始字符串x = 2+4*1*(2*(1+1)^2)^2+(4+5)^2(例如)
至x=2+4*1*64+81
- 首先搜索第一个“^”
- 获取上一个字符
- 如果有“)”
- 搜索前一个字符,同时找到“(”,但是如果在“(”之前找到“)”,则必须找到2个“(”;一个打开内部括号,第二个打开我想要pow的括号。
这是“(2+(3+4)+5)^2”的情况 ---> 返回“2+(3+4)+5”而不是“3+4)+5”。
现在替换为正确的表达式Math.pow("result","2")"并逐步计算 (1+1)^2 = 4 (2*4)^2 = 64
(4+5)^2 = 81
现在我终于可以使用 Interpreter.eval() 计算返回
非常感谢您的解答!
最佳答案
尝试使用以下代码来完成您的任务
String originalString ="x = 2+4*a*(b+c)^2";
String stringToInsert = "Math.pow((b+c),2)";
int startIndex = originalString.indexOf("(");
int endIndex = originalString.indexOf(")");
String firstPortion = originalString.substring(0,startIndex);
String lastPortion = originalString.substring(endIndex+1);
String finalString = firstPortion + stringToInsert + lastPortion;
System.out.println("finalString : "+finalString);
关于java - 获取括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501494/