Java 如何在GWT中替换StringTokenzier(…,true)?
我正在寻找与GWT兼容的StringTokenzier替代品,其中包括分隔符。该任务无法通过正则表达式解决,因为语法不是上下文无关的 示例:提取泛型类型定义的第一级。所以对于Java 如何在GWT中替换StringTokenzier(…,true)?,java,parsing,gwt,stringtokenizer,Java,Parsing,Gwt,Stringtokenizer,我正在寻找与GWT兼容的StringTokenzier替代品,其中包括分隔符。该任务无法通过正则表达式解决,因为语法不是上下文无关的 示例:提取泛型类型定义的第一级。所以对于列表、映射、集,我想要一个包含三项的列表列表和映射和设置 精简示例代码: private static List<String> extractFirstLevel(String type) { List<String> res = new LinkedList<String>()
列表、映射、集
,我想要一个包含三项的列表<代码>列表和映射
和设置
精简示例代码:
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;
}
private static List extractFirstLevel(字符串类型){
List res=new LinkedList();
StringTokenizer st=新的StringTokenizer(类型,,,true);
int nesting=0;//我们只对嵌套0感兴趣
字符串lastToken=“”;
而(st.hasMoreTokens()){
字符串标记=st.nextToken();
if(token.equals(“);
}else if(标记为等于(“,”)){
如果(嵌套==0){//我们对顶层感兴趣
res.add(lastToken);
lastToken=“”;
}否则{//这是a,在a<>内,所以我们不感兴趣
lastToken=lastToken+“,”;
}
}否则{
lastToken=lastToken+token.trim();
}
}
res.add(lastToken);
返回res;
}
我最终迭代了字符串中的字符:
private static List<String> extractFirstLevelNew(String type) {
List<String> res = new LinkedList<String>();
int start = 0;
int nesting = 0;
for (int i = 0; i < type.length(); i++) {
char chr = type.charAt(i);
if (chr == '<') {
nesting++;
} else if (chr == '>') {
nesting--;
} else if ((chr == ',') && (nesting == 0)) {
res.add(type.substring(start, i).trim());
start = i + 1;
}
}
res.add(type.substring(start, type.length()).trim());
return res;
}
private静态列表extractFirstLevelNew(字符串类型){
List res=new LinkedList();
int start=0;
int嵌套=0;
对于(int i=0;i
您可以使用String.split()方法。通常这是StringTokenizer的一个很好的替代方法,但我不知道让标记器返回分隔符的部分。我认为split()不会有任何用处,因为它只针对正则表达式设计。是的,尽管我的意思是您可以使用“,”进行拆分作为你的正则表达式。它可以工作,但是在你的标记器中你希望它返回分隔符,对吗?如果这是100%需要的话,那么你的StringTokenizer就不存在了(我知道)。