我该如何使用正则表达式拆分这个表达式?

3
我正在解决一个方程,但我希望使用常数来编写我的解决方案。
我正在使用的方法叫做分解,它将方程分解成常数。问题在于,当我分割一个带有负常数的方程时,会产生一个带有常数绝对值的数组。如何在仍然使用正则表达式的情况下实现减号?
如果输入是ax+by=c,输出应该是{a,b,c}
有用的奖励:是否有一种方法可以删除我拆分时创建的空元素?例如,如果我键入方程式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;
}

给定输入 2x+3y=6,您期望得到什么输出? - Tim Biegeleisen
一个整数数组,其值为 {2,3,6}。一般来说是 {a,b,c} - Ian L
1
如果输入是 x+y=5 呢? - anubhava
我忘了这个!好吧,这个程序只是为了我自己,所以我很高兴写下 1x+1y=5。不过,我很乐意接受解决这个问题的方案。 - Ian L
2个回答

2

这个问题的一般策略是按运算符拆分输入方程,然后在循环中提取系数。但是,有几种需要考虑的特殊情况:

  • 一个加号(+)被添加到任何不作为第一项出现的负数之前
  • 拆分后,通过检查空字符串可以检测到正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]));
    }
}

我终于设法让它工作了,但它仍然打印出绝对值而不是预期的常量(例如 -3 作为 3)。正如你所说,正则表达式删除了运算符。这可能是问题吗? - Ian L
@Tim,你不需要所有这些转义字符。这个等价:s.split("[-+*/=]") - Bohemian
@Bohemian 我在加减法中没有转义时遇到了编译器错误。 - Tim Biegeleisen
@TimBiegeleisen 谢谢!我现在明白了! - Ian L
1
@IanLimarta 最后一条评论:我更新了一次以处理另一个边缘情况,但目前看起来非常干净。 - Tim Biegeleisen
显示剩余7条评论

1
如果您正在使用java8,那么您可以使用这个一行代码的方法:
public static int[] decompose(String s) {
    return Arrays.stream(s.replaceAll("[^0-9]", " ").split("\\s+")).mapToInt(Integer::parseInt).toArray();
}

演示:

1. 输出

[2, 3, 6]

2. 代码

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        String s = "2x+3y=6";
        int[] array = decompose(s);
        System.out.println(Arrays.toString(array));
    }

    public static int[] decompose(String s) {
        return Arrays.stream(s.replaceAll("[^0-9]", " ").split("\\s+")).mapToInt(Integer::parseInt).toArray();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接