[英]How to parse polynomial for exponents
If given a String such as "(-2)x^(-2)+(3)x^(1)-(18)x^(-45)"
how would I use split() to get the exponents? 如果给出一个字符串,如
"(-2)x^(-2)+(3)x^(1)-(18)x^(-45)"
我将如何使用split()来获得指数? So this example would return [-2, 1, -45]
. 所以这个例子会返回
[-2, 1, -45]
。 I tried to figure out the regex notation but it's pretty confusing. 我试图找出正则表达式,但它很混乱。 The closest I've come is
string.split("x\\\\^\\\\(")
but it doesn't fully split it how I want to. 我最接近的是
string.split("x\\\\^\\\\(")
但它并没有完全按照我想要的方式拆分它。
Give this a try 试一试
String str = "(-2)x^(-2)+(3)x^(1)-(18)x^(-45)";
char[] chars = str.toCharArray();
List<String> exponents = new ArrayList<String>();
for(int i=0; i<chars.length; i++) {
if(chars[i] == '^') {
if(++i<chars.length && chars[i] == '(') {
StringBuilder sb = new StringBuilder();
while(++i<chars.length && chars[i] != ')') {
sb.append(chars[i]);
}
exponents.add(sb.toString());
}
}
}
Try this if you need a regex based solution: 如果您需要基于正则表达式的解决方案,请尝试此操作
String line = "(-2)x^(-2)+(3)x^(1)-(18)x^(-45)";
String pattern = ".*?\\^\\(([\\d-]+)\\)[\\+-]*";
Pattern r = Pattern.compile(pattern,Pattern.MULTILINE);
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println("Found value: " + m.group(1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.