import java io IOException import java util regex Pattern import java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.File;
import java.util.Scanner;
public class lab3 {
public static void main(String args[]){
try {
Scanner sc = new Scanner(new File("..\\lab3test.txt"));
String s = "";
while (sc.hasNext()){
s += sc.nextLine() + "\n";
}
String comment = "\\Q/*\\E(.|\\s)*?\\Q*/\\E";
String keyword = "(for|if|m1)";
String ident = "(([a-zA-Z]([0-9][a-zA-Z])*([0-9])?)|([0-9]([a-zA-Z][0-9])*([a-zA-Z])?))";
String pattern = "(^" + comment + ")|(^" + keyword + ")|(^" + ident + ")";
String patspace = "(^\\s+)";
String[] words = {"COMMENT", "COMMENT", "KEYWORD" , "IDENT", "IDENT"};
Pattern p = Pattern.compile(pattern);
Pattern ps = Pattern.compile(patspace);
int pos = 1, line = 1, linepos = 1;
boolean isError = false;
while (!s.equals("")) {
Matcher m = p.matcher(s);
if (m.find()) {
for (int i = 1; i <= 5; i++) {
isError = false;
if (m.group(i) != null) {
System.out.println(words[i - 1] + " (" + line + "," + linepos + "):" + m.group(i));
s = s.substring(m.end(i));
pos += m.end(i);
linepos += m.end(i);
if (i == 1 || i == 2) {
String l = m.group(i);
while (l.contains("\n")) {
l = l.substring(l.indexOf("\n") + 1);
line++;
}
linepos = l.length() + 1;
}
break;
}
}
continue;
}
m = ps.matcher(s);
if (m.find()){
isError = false;
String l = m.group();
pos += m.end();
while (l.contains("\n")) {
l = l.substring(l.indexOf("\n") + 1);
line++;
}
linepos = l.length() + 1;
s = s.substring(m.end());
continue;
}
if (!isError){
isError = true;
System.out.println("syntax error (" + line + "," + linepos + ")");
}
linepos++;
pos++;
s = s.substring(1);
}
} catch (IOException e) {
System.out.println("file not read\n");
}
}
}