Вывод соответствует требованию
package com.javarush.task.task19.task1918;
/*
Знакомство с тегами
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public static void main(String[] args) throws Exception{
args = new String[]{"b"};
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String file = reader.readLine();
reader.close();
BufferedReader fileReader = new BufferedReader(new FileReader(file));
String s;
StringBuilder sb = new StringBuilder();
while ((s = fileReader.readLine()) != null){
sb.append(s).append(" ");
}
fileReader.close();
String fileName = sb.toString();
//System.out.println(fileName);
String[] strings = fileName.split("[<>]");
Set<String> tegs = new HashSet<>();
for (String tegsString : strings){
//System.out.println(tegsString);
if (tegsString.contains("/")){
tegs.add(tegsString.substring(1));
}
}
for (int x = 0; x < strings.length-2;x++) {
/*if ((strings[x].contains(args[0]) && !strings[x].startsWith("/")) && (!strings[x+2].contains(args[0]) ||
(strings[x+2].contains(args[0]) && !strings[x+2].startsWith("/")))){
System.out.println(String.format("<%s></%s>",strings[x],args[0]));
}*/
if ((strings[x].contains(args[0]) && !strings[x].startsWith("/")) && (strings[x+2].contains(args[0]) && strings[x+2].startsWith("/"))){
System.out.println(String.format("<%s>%s<%s>",strings[x],strings[x+1],strings[x+2]));
}else if (strings[x].contains(args[0]) && !strings[x].startsWith("/")){
int tag = 0;
int slashTag = 0;
int indexFinish = 0;
StringBuilder sbTag = new StringBuilder();
for (int y = x; y < strings.length; y++){
if (strings[y].contains(args[0]) && !strings[y].startsWith("/")){
tag++;
}
if (strings[y].contains(args[0]) && strings[y].startsWith("/")){
slashTag++;
if (slashTag == tag){
indexFinish = y;
break;
}
}
}
if (slashTag == tag) {
for ( int z = x; z <= indexFinish; z++ ) {
boolean inSet = false;
for ( String strTegs : tegs ) {
if (strings[z].contains(strTegs)) {
inSet = true;
}
}
if (inSet) {
if (strings[z].endsWith(" ")) {
strings[z] = strings[z].substring(0, strings[z].length() - 1);
}
sbTag.append("<").append(strings[z]).append(">");
} else {
if (strings[z].endsWith(" ")) {
strings[z] = strings[z].substring(0, strings[z].length() - 1);
}
sbTag.append(strings[z]);
}
}
}
//x = indexFinish;
if (!sbTag.toString().isEmpty()) {
System.out.println(sbTag);
}
}
}
}
}