帮我用Java写一个分析关键字、标识符、数字、界符、运算符的词法分析程序
时间: 2023-07-04 10:19:41 浏览: 63
好的,以下是一个简单的基于正则表达式的词法分析程序,可以分析关键字、标识符、数字、界符和运算符:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LexicalAnalyzer {
public static void main(String[] args) {
String code = "int a = 1 + 2;\n" +
"if (a > 0) {\n" +
" System.out.println(\"Hello, world!\");\n" +
"}";
String[] lines = code.split("\\r?\\n");
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
int pos = 0;
while (pos < line.length()) {
char ch = line.charAt(pos);
// 匹配标识符
Pattern idPattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9]*");
Matcher idMatcher = idPattern.matcher(line.substring(pos));
if (idMatcher.lookingAt()) {
String id = idMatcher.group();
System.out.printf("Line %d: Identifier %s\n", i + 1, id);
pos += id.length();
continue;
}
// 匹配数字
Pattern numPattern = Pattern.compile("\\d+");
Matcher numMatcher = numPattern.matcher(line.substring(pos));
if (numMatcher.lookingAt()) {
String num = numMatcher.group();
System.out.printf("Line %d: Number %s\n", i + 1, num);
pos += num.length();
continue;
}
// 匹配关键字和运算符
switch (ch) {
case '(': System.out.printf("Line %d: Left Parenthesis\n", i + 1); pos++; break;
case ')': System.out.printf("Line %d: Right Parenthesis\n", i + 1); pos++; break;
case '{': System.out.printf("Line %d: Left Brace\n", i + 1); pos++; break;
case '}': System.out.printf("Line %d: Right Brace\n", i + 1); pos++; break;
case ';': System.out.printf("Line %d: Semicolon\n", i + 1); pos++; break;
case '=': System.out.printf("Line %d: Assignment\n", i + 1); pos++; break;
case '+': System.out.printf("Line %d: Plus\n", i + 1); pos++; break;
case '-': System.out.printf("Line %d: Minus\n", i + 1); pos++; break;
case '*': System.out.printf("Line %d: Multiply\n", i + 1); pos++; break;
case '/': System.out.printf("Line %d: Divide\n", i + 1); pos++; break;
default: pos++;
}
}
}
}
}
```
在这个程序中,我们先把代码按行分割,然后逐行进行词法分析。对于每一行,我们从左到右依次扫描字符,使用正则表达式匹配标识符和数字,使用 switch 语句匹配关键字、界符和运算符。
这个程序只是一个基本的示例,实际的词法分析程序要更复杂,需要考虑更多的语法规则,比如注释、字符串等等。