我如何用正则表达式拆分此表达式?

伊恩·利玛塔(Ian Limarta)

我正在努力求解方程式,但我想使用常量来编写我的解决方案。

我正在研究的方法称为分解,它将方程分解为常数。问题是,当我拆分时,具有负常数的方程将产生具有常数绝对值的数组。在仍使用正则表达式的情况下如何获得减号?

如果输入为ax+by=c,则输出应为{a,b,c}

有用的好处:有没有办法删除拆分时创建的空元素。例如,如果我键入equation 2x+3y=6,则最终得到一个包含元素的“原始”数组{2,,3,,6}

代码:

public static int[] decompose(String s)
{
    s = s.replaceAll(" ", "");

    String[] termRaw = s.split("\\D"); //Splits the equation into constants *and* empty spaces.
    ArrayList<Integer> constants = new ArrayList<Integer>(); //Values are placed into here if they are integers.
    for(int k = 0 ; k < termRaw.length ; k++)
    {
        if(!(termRaw[k].equals("")))
        {
            constants.add(Integer.parseInt(termRaw[k]));
        }

    }
    int[] ans = new int[constants.size()];

    for(int k = 0 ; k < constants.size(); k++) //ArrayList to int[]
    {
        ans[k] = constants.get(k);
    }
    return ans;
}
蒂姆·比格莱森(Tim Biegeleisen)

该答案的一般策略是通过运算符拆分输入方程,然后在循环中提取出系数。但是,有几种情况需要考虑:

  • +每个减号前面都加上一个加号(),该减号也不作为第一个术语出现
  • 拆分后,通过查看空字符串来检测系数为正的1
  • 拆分后,通过看到负号可以检测到负1的系数


String input = "-22x-77y+z=-88-10+33z-q";
input = input.replaceAll(" ", "")             // remove whitespace
             .replaceAll("=-", "-");          // remove equals sign
             .replaceAll("(?<!^)-", "+-");    // replace - with +-, except at start of line
// input = -22x+-77y+z+-88+-10+33z+-

String[] termRaw = bozo.split("[\\+*/=]");
// termRaw contains [-22x, -77y, z, -88, -10, 33z, -]

ArrayList<Integer> constants = new ArrayList<Integer>();
// after splitting,
// termRaw contains [-22, -77, '', -88, -10, 33, '-']
for (int k=0 ; k < termRaw.length ; k++) {
    termRaw[k] = termRaw[k].replaceAll("[a-zA-Z]", "");
    if (termRaw[k].equals("")) {
        constants.add(1);
    }
    else if (termRaw[k].equals("-")) {
        constants.add(-1);
    }
    else {
        constants.add(Integer.parseInt(termRaw[k]));
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章