确定Java

时间:2016-03-28 10:13:22

标签: java string

我正在尝试使用Lexer来确定输入中是否包含String / Integer / Double / etc。我已成功确定我是否处理除字符串以外的任何字符串,但我无法弄清楚如何处理字符串部分。

所以,让我说我有三个输入:

input = "\"asd\""
input2 = "\"The string \"String\" is really great\"5432"
input3 = "\"The string \"String\" is really great\"5432"\One more\""

Expected output from:
input = <STRING:asd> //Works with current code
input2 = <STRING:The string "String" is really great><INTEGER 5432> //Broken
input3 = <STRING:The string "String" is really great><INTEGER 5432> <STRING:One more>//ALSO BROKEN

输出处理完成并正常工作所以这不是问题,问题是处理字符串的结束方式。 它很容易处理不带引号的字符串,这是我目前处理它的方式:

    StringBuilder sb = new StringBuilder();
    int count = 1;
    pos++;
    current = input.charAt(pos);
    boolean last = false;
    char next = input.charAt(pos+1);
    while (current != '"'){
        sb.append(current);
        pos++;
        current = input.charAt(pos);
        next = input.charAt(pos+1);
    }
    tokens.add(new Token(TokenType.STRING,sb.toString()));

现在使用我的代码,当第一个引号出现在String中时会出现问题(例如,参见input2或input3)。我通过char检查输入char,而else-if分支由引号开头确定,这就是为什么有pos ++和当前更新(指的是&#39;输入2中的T&#39;例如)。

我怎样才能确定字符串是否已经结束(5432是input2中的整数而不是第一个字符串的一部分)?

1 个答案:

答案 0 :(得分:0)

所以基本上根据Lexer,输出STRING,INT,输入3的STRING在我的情况下是正确的,因为使用标记\"并不只是剪切它,我必须创建一个引号符号字符串,所以对于\\\"切割它:两个反斜杠中的第一个将显示反斜杠本身\,反斜杠和引号\"将在字符串中显示引号。总共显示的字符串为\",这只是引号的符号。