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 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(); } public ArrayList 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(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 mas1 = reader1.Read(); //System.out.println(reader1.Read()); // Сопоставление текста с регулярным выражением for (String line1 : mas1) { System.out.println(); //System.out.println("new line"); lex(line1, p); } } }