String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];
This should do it. Everything nicely stored in res.
String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];
This should do it. Everything nicely stored in res.
str.split (" ")
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)
In Java, how would I structure my regex to do a string split but only on commas, or commas followed by whitespace?
S4248 Regex patterns should not be created needlessly - false positive
Need help splitting string with regex
Split String every nth char / or the first occurrence of a period
**And round braces
Basically I have the following string split, but it breaks for multi word names. This is an example of the structure:
Sao Paulo, (-23.55, -46.63)
Where sArr is a string array, I attempted to match commas, whitespace and brackets, but didn't account for names with spaces.
sArr = line.split(("[\\s,(|)]+")); How could I match only commas, or commas with a whitespace, so that "Sao Paulo" doesn't turn into "Sao","Paulo"?
I'm trying to split a list of strings while keeping the delimiters ("+", "-" , "*" , "/") but I keep running into this problem where a string will also split at decimals as well. Given the input [-14.0x, -12.0] it will return [-, 14., 0x, -, 12., 0] but the expected result is [-, 14.0x, -, 12.0]. Any help is greatly appreciated.
private List<String> splitTerms(List<String> terms) {
List<String> splitTerms = new ArrayList<>();
for (String term : terms) {
String[] operatorAndTerms = term.split("(?<=[+-/*])");
for (String split : operatorAndTerms) {
splitTerms.add(split);
}
}
return splitTerms;
}