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)
Videos
**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"?
Why does Java still not have a function in the standard lib which allows to split a string by using characters/strings without interpreting its argument as regex? I can't believe that - am I missing something?
EDIT: Just to make it clear, I don't have performance issues. It's more a general question, because I thought that splitting a string by a non-regex is often needed thus it should exist somewhere without using a lib like apache commons. Also, using Pattern.quote doesn't quite lead to the best readable code. I think I will stick to apache then. Thanks guys!
Fact: String.split is error prone and slower.
without interpreting its argument as regex
In JDK, String.split actually splits w/o regex if your separator is a one non-regexp char, but it's an implementation detail...
IMHO, all String methods that take regexp String should be deprecated and replaced with a new version that takes explicit java.util.regex.Pattern param, e.g.: String.replaceAll(String, String) -> String.replaceAll(Pattern, String) (or even better: String.replaceAllSecondParamIsNOTWhatYouThink(Pattern, String) - not a joke - replaceAll is often used incorrectly)
StringTokenizer still exists.