import java util regex Matcher import java util regex Pattern import j

  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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.util.ArrayList;
class Reader {
private File openedFile_;
private BufferedReader reader_;
private ArrayList<String> readedText_;
public Reader(String path) {
openedFile_ = new File(path);
try {
reader_ = new BufferedReader(new InputStreamReader(new FileInputStream(openedFile_), "UTF-8"));
} catch (UnsupportedEncodingException exc) {
System.out.println(" UTF-8 exception. " + exc.getMessage());
} catch (FileNotFoundException exc) {
System.out.println("File Not Found. " + exc.getMessage());
}
readedText_ = new ArrayList<String>();
}
public ArrayList<String> Read() {
String currentString;
try {
while((currentString = reader_.readLine()) != null) {
readedText_.add(currentString);
}
} catch (IOException exc) {
System.out.println("IOException while reading file. " + exc.getMessage());
}
return new ArrayList<String>(readedText_);
}
}
public class IdentVsNumber
{
static int linecounter = 0;
static boolean waserror = false;
static int pos = 0;
public static void lex(String line1, Pattern p){
linecounter++;
pos = 0;
Matcher m;
do {
m = p.matcher(line1);
if (m.find()) {
if (waserror) {
waserror = false;
System.out.println("Ошибка"+" pos:"+linecounter+":"+pos);
}
if (m.group(1) != null){
System.out.println("Идентификатор␣" + m.group(1)+" pos:"+linecounter+":"+Integer.toString(m.end()+pos));
}
if (m.group(2) != null){
System.out.println("Число␣" + m.group(2)+" pos:"+linecounter+":"+Integer.toString(m.end()+pos));
}
if (m.group(3) != null){
System.out.println("Операция␣" + m.group(3)+" pos:"+linecounter+":"+Integer.toString(m.end()+pos));
}
pos+=m.end();
line1 = line1.substring(m.end());
} else
{
pos++;
//System.out.println("Ошибка");
if (line1.charAt(0) != ' ') {
waserror = true;
}
line1 = line1.substring(1);
}
} while (line1.length() != 0);
}
public static void main(String args[])
{
// Текст для сопоставления
String text = "";
// Регулярные выражения
String ident = "^[A-Za-z]+|^[(][0-9]+[)]";
String number = "^0|^[1-9][0-9]*";
String oper = "^[(][)]|^[:][=]|^[:]";
String pattern = "("+ident+")|("+number+")|("+oper+")";
// Компиляция регулярного выражения
Pattern p = Pattern.compile(pattern);
Reader reader1 = new Reader("lab3.txt");
ArrayList<String> mas1 = reader1.Read();
//System.out.println(reader1.Read());
// Сопоставление текста с регулярным выражением
for (String line1 : mas1) {
System.out.println();
//System.out.println("new line");
lex(line1, p);
}
}
}