I am looking for a GWT compatible replacement for a StringTokenzier which includes the delimiter. The task cannot be solved by regular expressions because the grammar is not context free.
Example: Extract the first level of a generic type definition. So for List<String>, Map<Integer, Map<Character, Boolean>>, Set<List<Double>>
, I want a list with three items. List<String>
and Map<Integer, Map<Character, Boolean>>
and Set<List<Double>>
Stripped down example code:
private static List<String> extractFirstLevel(String type) {
List<String> res = new LinkedList<String>();
StringTokenizer st = new StringTokenizer(type, "<>,", true);
int nesting = 0; // we are only interested in nesting 0
String lastToken = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equals("<")) {
nesting++; // ignore till matching >, but keep track of additional <
lastToken = lastToken + "<";
} else if (token.equals(">")) {
nesting--; // up one level
lastToken = lastToken + ">";
} else if (token.equals(",")) {
if (nesting == 0) { // we are interested in the top level
res.add(lastToken);
lastToken = "";
} else { // this is a , inside a < >, so we are not interested
lastToken = lastToken + ", ";
}
} else {
lastToken = lastToken + token.trim();
}
}
res.add(lastToken);
return res;
}