我很难在字符串中获取正确的标记。我只能采用诸如 (false,true,or,and,not,),()) 之类的标记。如果字符串中的标记是“(false”,那么我需要返回“(”和“false”。这就是我遇到问题的地方。
例如,我想要的输出是:
line: [ not (false or error true) ]
next token: [not]
next token: [(]
next token: [false]
next token: [or]
next token: [true]
next token: [)]
但我的输出是:
line: [ not (false or error true) ]
next token: [not]
next token: [(]
next token: [or]
next token: [true]
next token: [)]
在迭代扫描“or”的下一个标记时,我之前已经返回了“(”,并且我的下一个标记是“false”,但我不知道如何返回它。它会跳过它并返回“or” .
这是我的方法。
public boolean hasNext() {
if(!scan.hasNext()){
return false;
}
return true;
}
public String next() {
while(scan.hasNext()){
scan.useDelimiter(" ");
otherToken = scan.next();
if(otherToken.contains("(") || otherToken.contains(")")){
if(otherToken.contains("(")){
nextToken = otherToken.substring(1, otherToken.length());
return "(";
}
if(otherToken.contains(")")){
nextToken = ")";
return otherToken.substring(0, otherToken.length()-1);
}
}
if(otherToken.equals("true") || otherToken.equals("false") ||
otherToken.equals("or") || otherToken.equals("and") ||
otherToken.equals("not")){
nextToken = otherToken;
return nextToken;
}
if(otherToken.equals("(") || otherToken.equals(")")){
nextToken = otherToken;
return nextToken;
}
else{
continue;
}
}
return nextToken;
}
最佳答案
通过对分隔符正则表达式模式进行一些调整,您可以让 java Scanner 返回您想要的标记:
String line =" not (false or error true) ";
Scanner scan = new Scanner(line);
scan.useDelimiter(
"(?<=(?:\\b(?:false|true|or|and|not)\\b)|[()]|^)" // lookbehind
+".*?" // non-greedy match all
+"(?=(?:\\b(?:false|true|or|and|not)\\b)|[()]|$)"); // lookahead
while(scan.hasNext()) {
System.out.format("next token: [%s]%n", scan.next());
}
输出:
next token: [not]
next token: [(]
next token: [false]
next token: [or]
next token: [true]
next token: [)]
但是,仅使用正则表达式来查找标记本身会简单得多:
String line = "not (false or error true)";
Pattern p = Pattern.compile("(?:\\b(?:false|true|or|and|not)\\b)|[()]");
Matcher m = p.matcher(line);
while(m.find()) {
System.out.format("next token: [%s]%n", m.group());
}
关于java - 如何在另一个调用中正确返回 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42429584/