java - 如何在另一个调用中正确返回 token ?

标签 java iterator token

我很难在字符串中获取正确的标记。我只能采用诸如 (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/

相关文章:

java - 1970 年 1 月 1 日之前的日期

c# - CreateProcessWithTokenW winapi 返回 false 但没有原因

java - 设置 Mavens Java 版本

java - 如何分析Websphere core*.dmp文件和Snap*.trc文件?

c++ - 取消引用字符串迭代器将无法编译

c# - 带反射的 yield 迭代器

c++ - 关于模板函数实例化的编译时错误

azure - 内置注册/登录策略 Azure B2C 声明的默认值

python - 我应该在 Django Rest Framework 中使用 JWT 还是 Basic Token 身份验证?

java - java如何进行负数的模计算?