爪哇
调用你的词法分析器的setText(...)
方法:
grammar T;
parse
: words EOF {System.out.println($words.text);}
;
words
: Word (Spaces Word)*
;
Word
: ('a'..'z'|'A'..'Z')+
;
Spaces
: (' ' | '\t' | '\r' | '\n')+ {setText(" ");}
;
可以使用以下课程进行测试:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) throws Exception {
String source = "This is \n just \t\t\t\t\t\t a \n\t\t test";
ANTLRStringStream in = new ANTLRStringStream(source);
TLexer lexer = new TLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
TParser parser = new TParser(tokens);
System.out.println("------------------------------\nSource:\n" + source +
"\n------------------------------\nAfter parsing:");
parser.parse();
}
}
产生以下输出:
------------------------------
Source:
This is
just a
test
------------------------------
After parsing:
This is just a test
Puneet Pawaia写道:
非常感激任何的帮助。出于某种原因,我发现很难理解 ANTLR。有什么好的教程吗?
ANTLR Wiki有大量信息丰富的信息,尽管有点非结构化(但那可能就是我!)。
最好的 ANTLR 教程是这本书:The Definitive ANTLR Reference: Building Domain-Specific Languages。
C#
对于 C# 目标,试试这个:
grammar T;
options {
language=CSharp2;
}
@parser::namespace { Demo }
@lexer::namespace { Demo }
parse
: words EOF {Console.WriteLine($words.text);}
;
words
: Word (Spaces Word)*
;
Word
: ('a'..'z'|'A'..'Z')+
;
Spaces
: (' ' | '\t' | '\r' | '\n')+ {Text = " ";}
;
与测试类:
using System;
using Antlr.Runtime;
namespace Demo
{
class MainClass
{
public static void Main (string[] args)
{
ANTLRStringStream Input = new ANTLRStringStream("This is \n just \t\t\t\t\t\t a \n\t\t test");
TLexer Lexer = new TLexer(Input);
CommonTokenStream Tokens = new CommonTokenStream(Lexer);
TParser Parser = new TParser(Tokens);
Parser.parse();
}
}
}
这也打印This is just a test
到控制台。我尝试使用SetText(...)
而不是,setText(...)
但这也不起作用,并且C# API 文档当前处于脱机状态,因此我使用了 trial and error-hack {Text = " ";}
。我用C# 3.1.1 运行时 DLL 的.
祝你好运!