帮我用Java写一个关键字、标识符、数字、界符、运算符的词法分析程序
时间: 2023-07-04 12:19:45 浏览: 50
好的,以下是一个简单的基于正则表达式的词法分析程序,可以分析关键字、标识符、数字、界符和运算符:
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LexicalAnalyzer {
public static void main(String[] args) {
// 输入的代码
String code = "int a = 123;\n" +
"if (a > 0) {\n" +
" System.out.println(\"Hello, world!\");\n" +
"}";
// 关键字集合
Set<String> keywords = new HashSet<>(Arrays.asList(
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char",
"class", "const", "continue", "default", "do", "double", "else", "enum",
"extends", "final", "finally", "float", "for", "if", "goto", "implements",
"import", "instanceof", "int", "interface", "long", "native", "new", "package",
"private", "protected", "public", "return", "short", "static", "strictfp",
"super", "switch", "synchronized", "this", "throw", "throws", "transient",
"try", "void", "volatile", "while"
));
// 界符集合
Set<Character> delimiters = new HashSet<>(Arrays.asList(
'(', ')', '{', '}', ';'
));
// 运算符集合
Set<String> operators = new HashSet<>(Arrays.asList(
"+", "-", "*", "/", "%", "++", "--", "==", "!=",
">", "<", ">=", "<=", "&&", "||", "!", "&", "|", "^", "~", "<<", ">>", ">>>",
"+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", ">>>="
));
// 匹配标识符的正则表达式
String idPatternStr = "[a-zA-Z_$][a-zA-Z0-9_$]*";
// 匹配数字的正则表达式
String numPatternStr = "\\d+(\\.\\d+)?([eE][+-]?\\d+)?";
// 分行
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);
// 跳过空白字符
if (Character.isWhitespace(ch)) {
pos++;
continue;
}
// 匹配标识符
Pattern idPattern = Pattern.compile(idPatternStr);
Matcher idMatcher = idPattern.matcher(line.substring(pos));
if (idMatcher.lookingAt()) {
String id = idMatcher.group();
if (keywords.contains(id)) {
System.out.printf("Line %d: Keyword %s\n", i + 1, id);
} else {
System.out.printf("Line %d: Identifier %s\n", i + 1, id);
}
pos += id.length();
continue;
}
// 匹配数字
Pattern numPattern = Pattern.compile(numPatternStr);
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;
}
// 匹配界符和运算符
if (delimiters.contains(ch)) {
System.out.printf("Line %d: Delimiter %s\n", i + 1, ch);
pos++;
} else {
for (int len = Math.min(operators.size(), line.length() - pos); len > 0; len--) {
String op = line.substring(pos, pos + len);
if (operators.contains(op)) {
System.out.printf("Line %d: Operator %s\n", i + 1, op);
pos += len;
break;
}
}
}
}
}
}
}
```
在这个程序中,我们先把代码按行分割,然后逐行进行词法分析。对于每一行,我们从左到右依次扫描字符,使用正则表达式匹配标识符和数字,使用集合匹配关键字、界符和运算符。
这个程序只是一个基本的示例,实际的词法分析程序要更复杂,需要考虑更多的语法规则,比如注释、字符串等等。