Проверил уже все варианты, которые мог придумать, много раз переписывал обработку, но валидацию упорно не могу пройти. Похоже, я не вижу какого-то очевидного другим варианта тега. Просьба помочь.
package com.javarush.task.task19.task1918;
/*
Знакомство с тегами
*/
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public static Integer getPos(String str, Pattern patt) {
Matcher matcher = patt.matcher(str);
if (matcher.find()) {
return matcher.start();
} else {
return null;
}
}
public static String getTag(String str, Pattern patt) {
Matcher matcher = patt.matcher(str);
if (matcher.find()) {
return matcher.group();
} else {
return null;
}
}
public static void main(String[] args) {
// String tag = "a";
// String str = "<a ><b-></a><1><a><d/><a\n\r>";
// Pattern begPatt = Pattern.compile("<" + tag + "[\\p{Space}|\\p{Cntrl}]*>");
// Pattern endPatt = Pattern.compile("</" + tag + ">");
String fileName = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(fileName);
// System.out.println(args[0]);
if ((fileName == null) || (args.length == 0) || (args[0] == null)) {
return;
}
Pattern begPatt = Pattern.compile("<" + args[0]);
Pattern endPatt = Pattern.compile("</" + args[0] + ">");
int cntTagOpen = 0;
Integer posBeg = null;
Integer posEnd = null;
String str = null;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while (reader.ready()) {
str = reader.readLine();
while (str != null && !str.equals("")) {
if (cntTagOpen == 0) {
posBeg = getPos(str, begPatt);
if (posBeg != null) {
cntTagOpen++;
System.out.print(getTag(str, begPatt));
str = str.substring(posBeg + getTag(str, begPatt).length());
if (str.equals("")) {
System.out.println("");
}
} else {
str = null;
}
} else {
posBeg = getPos(str, begPatt);
posEnd = getPos(str, endPatt);
if ((posBeg == null && posEnd != null) || (posBeg != null && posEnd != null && posEnd < posBeg)) {
System.out.print(str.substring(0, posEnd + getTag(str, endPatt).length()));
cntTagOpen--;
if (cntTagOpen == 0) {
System.out.println("");
}
str = str.substring(posEnd + getTag(str, endPatt).length());
} else if (posBeg != null && posBeg >= 0) {
cntTagOpen++;
System.out.println(str.substring(0, posBeg));
System.out.print(str.substring(posBeg, getTag(str, begPatt).length()));
str = str.substring(posBeg - 1 + getTag(str, begPatt).length());
if (str.equals("")) {
System.out.println("");
}
} else {
System.out.print(str);
str = null;
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
};
}
}