简体   繁体   English

使用String作为正则表达式时,String []。split(String regex)不会完全拆分

[英]String[].split(String regex) will not split at all when using String as regex

I'm trying to read a polynomial in my format that would add together constant with the same variable and for that I need to split out constant and variable apart from "x^" but when I try to use the .split() method it doesn't split at all and just puts the whole string into the first cell of the array. 我正在尝试以我的格式读取多项式,该多项式会将常量和相同的变量加在一起,为此,我需要将常量和变量除“ x ^”之外,但是当我尝试使用.split()方法时,根本不会拆分,只是将整个字符串放入数组的第一个单元格中。

// Splitting terms into constants and variables:
String splitTerms[][] = new String[terms.size()][2];
for (int i = 0; i < terms.size(); i++) {
    String tempTerm = terms.get(i);
    if (tempTerm.indexOf("x^") >= 0) {
        // Here is where the problem occurs:
        splitTerms[i] = tempTerm.split("x^");
    }
    else if (tempTerm.indexOf("x") >= 0) {
        splitTerms[i][0] = tempTerm.substring(0, tempTerm.length()-1);
        splitTerms[i][1] = "1";
    }
    else {
        splitTerms[i][0] = tempTerm;
        splitTerms[i][1] = "0";
    }
}

If anyone knows why this happens or what do I do to fix it, I would really appreciate the help! 如果有人知道为什么会发生这种情况或我要采取什么措施加以解决,我将非常感谢您的帮助!

split() uses regex, and ^ is a special character, so you'll need to escape the ^ : split()使用正则表达式,并且^是特殊字符,因此您需要转义^

tempTerm.split("x\\^");

Which for the String "2x^2" will output: 对于String “ 2x ^ 2”,将输出:

[2, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM