javaregexsplitextraction-operator

split and extract Operator from Operand with Regex


I have an Equation that includes Operator and Operand. I want to split it and extract the Operator and Operand in one String array like this:

4+3 -2 + 1* 5 -2

4,+,-,2,+,1,*,5,-,2

Does anyone have a suggested Regex pattern for this?


Solution

  • Here is a way to do it with regex, haven't used these much so might be able to be improved.

    Pattern pattern = Pattern.compile("[0-9]+|(\\+|-|\\*)");
    Matcher matcher = pattern.matcher("4+3 -2 + 1* 5 -2");
    List<String> parts = new ArrayList<>();
    while (matcher.find()) {
        parts.add(matcher.group());
    }
    String[] array = parts.toArray(new String[parts.size()]);
    System.out.println(Arrays.toString(array));
    

    Outputs:

    [4, +, 3, -, 2, +, 1, *, 5, -, 2]