Can I use an String array within split() to specifier delimiters?

Viewed 71

New to java/coding and trying to get to grips with it so thank you in advance for the help!

I have this string "s" I am splitting using a set of operators as delimiters.

String[] workableParts = s.split("(?<=[-+*/%^=])|(?=[-+*/%^=])");

I'm storing each split within the workableParts array with the delimiters also stored as part of the array - so for instance an input of 7+7 would be stored as:

workableParts[0]="7" workableParts[1]="+" workableParts[2]="7"

I also use this operator array elsewhere:

private String[] ops = {"-","+","*","/","%","^","="};

Is there a way I can use this to replace the text in the split above but maintain the same effect? The idea being that if I add operators at a later date I only have to update them in one place.

Many thanks,

Sam

2 Answers

One possible option is to convert your string array to a string using Arrays.toString(ops); and use that in the regex expression. This returns the string of the form [-,+,*,/,...].

Now, you can replace the , with an empty string "" and use the substring in your regex.

private String[] ops = {"-","+","*","/","%","^","="};
String joinedOps = Arrays.toString(strArray);
joinedOps = joinedOps.substring(1, str.length()-1).replace(",", "");
String regex = "...."+joinedOps+"...";

You could do something like this. Define you own split method and build the regex inside of it. When you change the ops array you will modify the regex.

Note: You must use caution in the placement of the ops so that they don't construct an unexpected character class. E.g. - should be at the front and ^ should never be.

static String[] ops = { "-", "+", "*", "/", "%", "^", "=" };

public static void main(String[] args) {
        String s = "7+7-8^2";

        String[] workableParts = opSplit(s);        
        System.out.println(Arrays.toString(workableParts));     
}

Prints

[7, +, 7, -, 8, ^, 2]

The method


public static String[] opSplit(String s) {
    String op = String.join("", ops);
    String regex = "(?<=[" + op + "])|(?=[" + op + "])";
    return s.split(regex);
}
Related