实验要求
要求对一个 Java 程序进行简单的词法分析,找出其中用到的关键字、变量类型、变量名、方 法名以及操作运算符,并分别打印出来。 注意 考虑如果 (、{ 字符与关键字或变量名相连的情况下该怎么处理,尽可能将代码写完善。
挺简单的,用正则一下就出来了,直接放代码吧 基本上都考虑到了吧qaq,方法的话默认大家都用public了,不考虑其他情况
package exp03;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CodeAnalysis {
public static void main(String[] args) {
String fileName = "C:\\Users\\CrazyBin\\IdeaProjects\\Exp03\\src\\exp03\\codeDemo";
String regexKeyWords = "abstract|assert|boolean|break|case|catch|"
+ "class|const|continue|default|do|double|else"
+ "|extends|false|final|finally|for|goto|if|implements|"
+ "import|instanceof|interface|native|new|null|"
+ "package|privat|protected|public|return|static|"
+ "strictfp|super|switch|synchronized|this|throw|throws|true|"
+ "transient|try|void|volatile|while";
String regexVariableType = "int|double|float|enum|long|byte|boolean|char|String|short";
String regexMethod = "(public\\s+)?(static\\s+)?\\w+(\\[\\])?\\s+\\w+(\\s)?\\((\\w+(\\[\\])?\\s+\\w+(\\s+)?\\,)*(\\w+(\\[\\])?\\s+\\w+)?(\\s+)*\\)\\s{1}";
String regexVariable = "(private\\s+)?(static\\s+)?(int|double|float|enum|long|byte|boolean|char|String|short)(\\[\\])?\\s+\\S";
String regexOperator = "(\\+|\\-|\\*|\\/)";
StringBuilder stringBuilder = new StringBuilder();
try {
FileInputStream inputStream = new FileInputStream(fileName);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int temp = 0;
while (temp != -1) {
temp = bufferedInputStream.read();
stringBuilder.append((char) temp);
}
System.err.println("程序的关键字,变量类型,方法,变量名,操作符统计如下:");
bufferedInputStream.close();
inputStream.close();
search(regexKeyWords,stringBuilder);
search(regexVariableType,stringBuilder);
search(regexMethod,stringBuilder);
search(regexVariable,stringBuilder);
search(regexOperator,stringBuilder);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void search(String regex,StringBuilder stringBuilder)
{
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(stringBuilder);
while(matcher.find())
{
System.out.println(matcher.group());
}
}
}
运行截图
截了一部分
|