示例:SimpleSelectParser 解析 select 1+1; 输出 2;
0)总结
编写 JavaCC 模板,*.jj 文件。
编译生成代码文件。
移动代码文件到对应的包下。
调用生成的代码文件。
1)JavaCC 模板
main/javacc/SimpleSelectParser.jj
options {
IGNORE_CASE = true;
// 允许被多次初始化
STATIC = false;
}
PARSER_BEGIN(SimpleSelectParser)
package cn.com.ptpress.cdm.parser.select;
import java.io.* ;
public class SimpleSelectParser {
private String sql;
public void parse() throws ParseException {
SelectExpr(sql);
}
public SimpleSelectParser(String expr) {
this((Reader)(new StringReader(expr)));
this.sql = expr;
}
public static void main(String[] args) throws Exception{
final SimpleSelectParser parser = new SimpleSelectParser(String.join(" ", args));
parser.parse();
}
}
PARSER_END(SimpleSelectParser)
void SelectExpr(String sql) :
{
int res;
}
{
<SELECT>
res = Expression()
{
System.out.println(sql + "=" + res);
}
}
int Expression() :
{
int res = 0;
int v;
}
{
res = Number()
(
<ADD>
v = Number()
{res += v;}
|
<SUB>
v = Number()
{res -= v;}
)*
{return res;}
}
int Number() :
{
Token t;
}
{
t = <NUMBER>
{
return Integer.parseInt(t.image);
}
}
TOKEN :
{
< SELECT: "SELECT" >
| < NUMBER: (["0"-"9"])+ >
| < ADD: "+" >
| < SUB: "-" >
}
/*
跳过的制表符
* */
SKIP :
{
" "
| "\t"
| "\n"
| "\r"
| "\f"
}
2)Java CC 的 Maven 插件
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>javacc-maven-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>generate-sources</phase>
<id>javacc</id>
<goals>
<goal>javacc</goal>
</goals>
<configuration>
<sourceDirectory>${basedir}/src/main/javacc</sourceDirectory>
<includes>
<include>**/*.jj</include>
</includes>
<!-- <lookAhead>2</lookAhead>-->
<!-- <isStatic>false</isStatic>-->
<outputDirectory>${basedir}/generated-sources/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
3)执行编译命令
mvn org.codehaus.mojo:javacc-maven-plugin:2.6:javacc
生成的文件:
4)主类调用
1.将生成的文件移动到 .jj 文件配置的包下
2.启动 TestParser 类
package cn.com.ptpress.cdm.parser.select;
public class TestParser {
public static void main(String[] args) throws ParseException {
parseSelect("select 1+1");
parseSelect("select 1+1+1");
parseSelect("select 1 + 3 - 5");
}
private static void parseSelect(String sql) throws ParseException {
final SimpleSelectParser parser = new SimpleSelectParser(sql);
// 解析的核心方法
parser.parse();
}
}