我正在寻找一个兼容GWT的StringTokenzier替代品,其中包含分隔符。正则表达式无法解决该任务,因为语法不是上下文无关的。
示例:提取泛型类型定义的第一级。因此,对于列表<;字符串>;,地图<;整数,映射<;字符,布尔值>>;,设置<;列表<;双倍>>
,我想要一个有三个项目的列表<代码>列表<;字符串>和地图<;整数,映射<;字符,布尔值>>
和设置<;列表<;双倍>>密码
删除示例代码:
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;
}