为什么'a'..'z'在 ANTLR 中匹配通配符,例如 $ 或 £

发布于 2024-09-08 08:55:36 字数 178 浏览 2 评论 0原文

当我运行以下语法时:

test : WORD+;

WORD : ('a'..'z')+;
WS : ' '+ {$channel = HIDDEN;};

并且输入“?test”时,为什么antlr接受它作为有效输入?我认为 ('a'..'z') 只会匹配小写字母中的字符?

When I run the following grammer:

test : WORD+;

WORD : ('a'..'z')+;
WS : ' '+ {$channel = HIDDEN;};

and I give the input "?test" why does antlr accept this as valid input? I thought the ('a'..'z') would only match characters within the lowercase alphabet?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

謌踐踏愛綪 2024-09-15 08:55:36

当使用您发布的语法解析输入字符串 ?test 时,ANTLR 确实会产生错误。通常情况下,错误在于 ANTLR 周围使用的工具(不幸的是,我发现 ANTLRWorks 也经常发生这种情况!)。

要自行测试(正确),请创建一个文件 Test.g:

grammar Test;

test : WORD+;

WORD : ('a'..'z')+;

WS   : ' '+ {$channel = HIDDEN;};

和一个文件 Main.java:

import org.antlr.runtime.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("?test");
        TestLexer lexer = new TestLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TestParser parser = new TestParser(tokens);
        parser.test();
    }
}

并下载 ANTLR 3.2 JAR 在同一目录中。

现在生成一个词法分析器 &解析器:

java -cp antlr-3.2.jar org.antlr.Tool Test.g 

编译所有 Java 源文件:

javac -cp antlr-3.2.jar *.java

并运行 Main 类:

java -cp .:antlr-3.2.jar Main 

(如果使用的是 Windows,请将 : 替换为 ;!)

将产生以下错误消息:

line 1:0 no viable alternative at character '?'

ANTLR does produce an error when parsing the input string ?test with the grammar you posted. As is usually the case, the error lies with the tool being used around ANTLR (I see it happen a lot with ANTLRWorks as well, unfortunately!).

To test it yourself (properly), create a file Test.g:

grammar Test;

test : WORD+;

WORD : ('a'..'z')+;

WS   : ' '+ {$channel = HIDDEN;};

and a file Main.java:

import org.antlr.runtime.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("?test");
        TestLexer lexer = new TestLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TestParser parser = new TestParser(tokens);
        parser.test();
    }
}

and download a copy of the ANTLR 3.2 JAR in the same directory.

Now generate a lexer & parser:

java -cp antlr-3.2.jar org.antlr.Tool Test.g 

compile all Java source files:

javac -cp antlr-3.2.jar *.java

and run the Main class:

java -cp .:antlr-3.2.jar Main 

(replace the : with ; if you're on Windows!)

which will produce the following error message:

line 1:0 no viable alternative at character '?'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文