Java 将单个senerio与ANTLR匹配,并将其他所有内容作为噪声跳过

Java 将单个senerio与ANTLR匹配,并将其他所有内容作为噪声跳过,java,parsing,coldfusion,antlr,Java,Parsing,Coldfusion,Antlr,我使用ANTLR V4 Eclipse插件定义了一个简单的语法。我想解析一个包含Coldfusion cfscript代码的文件,并找到属性定义的每个实例。例如: property name="productTypeID" ormtype="string" length="32" fieldtype="id" generator="uuid" unsavedvalue="" default=""; 也就是说,属性关键字后跟任意数量的属性,行以分号结尾 .g4文件 grammar CFPrope

我使用ANTLR V4 Eclipse插件定义了一个简单的语法。我想解析一个包含Coldfusion cfscript代码的文件,并找到属性定义的每个实例。例如:

property name="productTypeID" ormtype="string" length="32" fieldtype="id" generator="uuid" unsavedvalue="" default="";
也就是说,属性关键字后跟任意数量的属性,行以分号结尾

.g4文件

grammar CFProperty;
property  : 'property ' (ATR'='STRING)+EOL; // match keyword property followed by an attribute definition

ATR : [a-zA-Z]+;                            // match lower and upper-case identifiers name

STRING: '"' .*? '"';                        // match any string

WS : [ \t\r\n]+ -> skip;                    // skip spaces, tabs, newlines

EOL : ';';                                  // end of the property line
我创建了一个简单的java项目,它使用生成的解析器、树遍历器等来打印这些匹配的出现

我正在测试的输入是:

"property id=\"actionID\" name=\"actionName\" attr=\"actionAttr\"    hbMethod=\"HBMethod\"; public function some funtion  {//some text} property name=\"actionID\" name=\"actionName\" attr=\"actionAttr\" hbMethod=\"HBMethod\"; \n more noise "
我的问题是,这只是匹配:

property id="actionID" name="actionName" attr="actionAttr"    hbMethod="HBMethod";
因为它不理解所有其他的东西都是噪声,所以它与属性定义的第二个实例不匹配


如何在属性定义的多个实例上进行匹配,并在两者之间的所有其他实例上进行匹配,作为要跳过的噪波?

您可以使用lexer模式来执行所需操作。一种模式用于属性和填充,另一种模式用于噪波。模式背后的想法是从一个模式(一个状态)转到另一个我们在词法分析操作中发现的标记

要做到这一点,您必须将语法分为两个文件,一个文件是解析器,另一个文件是lexer

这是lexer部分(在我的例子中,名为
TestLexer.g4

下面是解析器部分(在我的例子中,名为
Test.g4

这应该可以完成以下工作:)

lexer grammar TestLexer;

// Normal mode

PROPERTY : 'property';
EQUALS : '=';
ATR : [a-zA-Z]+;                           // match lower and upper-case identifiers name
STRING: '"' .*? '"';                       // match any string
WS : [ \t\r\n]+        -> skip;            // skip spaces, tabs, newlines
EOL : ';'              -> pushMode(NOISE); // when ';' is found, go to noise mode where everything is skip

mode NOISE;

NOISE_PROPERTY : 'property' -> type(PROPERTY), popMode;   // when 'property' is found, we say it's a PROPERTY token and we go back to  normal mode
ALL :  .+?                  -> skip;                      // skip all other stuffs
grammar Test;

options { tokenVocab=TestLexer; }

root : property+;
property  : PROPERTY (ATR EQUALS STRING)+ EOL; // match keyword   property followed by an attribute definition