Issue
I want to split a string along several different conditions - I understand there is a Java String method called String.split(element), which splits the String into an array based on the element specified.
However, splitting among more objects seems to be very complex -- especially if the split must occur to a range of elements.
Precisely, I want java to split the string
"a>=b" into {"a",">=","b"}
"a>b" into {"a", ">", "b"}
"a==b" into {"a","==","b"}
I have been fiddling around with regex too just to see how to split it exactly based on this parameters, but the closest I've gotten is just splitting along a single character.
EDIT: a and b are arbitrary Strings that can be of any length. I simply want to split along the different kinds of comparators ">",">=","==";
For example, a could be "Apple" and b could be "Orange".
So in the end I want the String from "Apple>=Orange" into {"Apple", ">=", "Orange"}
Solution
You can use regular expressions. No matter if you use a, or b or abc for your variables you'll get the first variable in the group 1, the condition in the group 2 and the second variable in the group 3.
Pattern pattern = Pattern.compile("(\\w+)([<=>]+)(\\w+)");
Matcher matcher = pattern.matcher("var1>=ar2b");
if(matcher.find()){
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
}
Answered By - reos