Match strings in antlr characters: what am I doing wrong?

I have been using antlr for 3 days. I can parse expressions, write Listeners, interpret parsing trees ... it's a dream.

But then I tried to match the letter string "foo%", and I failed. I can find many examples that claim this. I tried them all.

So, I created a tiny project to fit a string string. I have to do something stupid.

grammar Test;

clause
  : stringLiteral EOF
  ;

fragment ESCAPED_QUOTE : '\\\'';
stringLiteral :   '\'' ( ESCAPED_QUOTE | ~('\n'|'\r') ) + '\'';

A simple test:

public class Test {

    @org.junit.Test
    public void test() {
        String input = "'foo%'";
        TestLexer lexer = new TestLexer(new ANTLRInputStream(input));
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TestParser parser = new TestParser(tokens);
        ParseTree clause = parser.clause();
        System.out.println(clause.toStringTree(parser));

        ParseTreeWalker walker = new ParseTreeWalker();
    }
}

Result:

Running com.example.Test
line 1:1 token recognition error at: 'f'
line 1:2 token recognition error at: 'o'
line 1:3 token recognition error at: 'o'
line 1:4 token recognition error at: '%'
line 1:6 no viable alternative at input '<EOF>'
(clause (stringLiteral ' ') <EOF>)
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.128 sec - in com.example.Test

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

A complete constructed build tree is available for a quick overview here.

31 lines of code ... most of them are borrowed from small examples.

 $ mvn clean test

Using antlr-4.5.2-1.

+4
1

fragment . , stringLiteral lexer. .

, ~('\n'|'\r'), , , :

clause
  : StringLiteral EOF
  ;

StringLiteral :   '\'' ( Escape | ~('\'' | '\\' | '\n' | '\r') ) + '\'';

fragment Escape : '\\' ( '\'' | '\\' );
+2

All Articles