我有一个任务是创建一个词法分析器,将语言翻译成一系列标记。我正在使用 java.util.regex 通过一个字符串来查找不同的标记,然后将它们放入一个数组中,我将通过该数组为它们分配各自的标记。这是我的程序的一部分:
public static void main(String args[]) throws FileNotFoundException, IOException{
String[] symbols = {"+","-","*","/","<","<=",">",">=","==","!=","=",";",",",".","(",")","[","]","{","}","/*","*/","//"};
String[] input;
FileInputStream fstream = new FileInputStream("src\\testCode.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
StringBuilder sb = new StringBuilder();
String s;
String ret = "";
while((s = br.readLine()) != null){
sb.append(s);
}
ret = sb.toString();
input = regexChecker("regex goes here",ret);
for (int i = 0; i < input.length; i++) {
System.out.println(input[i]);
}
System.out.println(input.length);
in.close();
}
public static String[] regexChecker(String theRegex, String str2Check){
List<String> allMatches = new ArrayList<String>();
Pattern checkRegex = Pattern.compile(theRegex);
Matcher regexMatcher = checkRegex.matcher(str2Check);
while(regexMatcher.find()){
//regexInput = new String[regexMatcher.group().length()];
allMatches.add(regexMatcher.group());
}
String[] regexInput = allMatches.toArray(new String[allMatches.size()]);
return regexInput;
}
我的问题是:是否有一个正则表达式可以分隔这种语言?或者我是否通过尝试只使用一个正则表达式来完成我的任务?一些词汇约定是:标识符以小写字母或下划线的大写开头,后跟任何单词字符。允许使用注释行和块。数字是十进制的无符号整数或实数。并且有 int、double、if 等关键字和 *、/、+ 等特殊符号。
我可以为每个单独的约定制作正则表达式,但我不确定如何将它们组合成 1,正如我的程序需要的那样。
我也将(?://.*)|(/\\*(?:.|[\\n\\r])*?\\*/)
其用作评论的正则表达式,但它似乎不适用于评论行,仅适用于评论块。将文件读入单行字符串的方式可能是原因吗?