I have worked on this for hours and this is probably the best i could do .. please help.
package com.codegym.task.task19.task1918;
/*
Introducing tags
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
String tagName = args[0];
String tagNameStart = "<" + tagName;
String tagNameClose = "</" + tagName + ">";
// String fileName = "C:/Users/Dan/Desktop/codegym test files/testTag.txt";
// String tagNameStart = "<span";
// String tagNameClose = "</span>";
String combinedTags = "";
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
while (bufferedReader.ready()) {
combinedTags += bufferedReader.readLine();
}
bufferedReader.close();
// System.out.println(combinedTags);
ArrayList<Integer> startIndexList = new ArrayList<>();
ArrayList<Integer> endIndexList = new ArrayList<>();
// adding the beginning and ending indexes to the list as per the ,as per the tag.
Pattern pattern1 = Pattern.compile(tagNameStart);
Pattern pattern2 = Pattern.compile(tagNameClose);
Matcher matcher1 = pattern1.matcher(combinedTags);
Matcher matcher2 = pattern2.matcher(combinedTags);
while(matcher1.find() && matcher2.find()) {
startIndexList.add(matcher1.start());
endIndexList.add(matcher2.end());
}
// for (int i : startIndexList) {
// System.out.print(i + " ");
// }
// System.out.println();
// for (int i : endIndexList) {
// System.out.print(i + " ");
// }
// System.out.println();
// final logic to print each of the tags in new line.
for(int i = 1; i < endIndexList.size(); i++) {
int beginIndex = 0;
int endIndex = 0;
if (endIndexList.get(i - 1) > startIndexList.get(i)) {
beginIndex = startIndexList.get(i -1);
endIndex = endIndexList.get(i);
System.out.println(combinedTags.substring(beginIndex, endIndex));
System.out.println(combinedTags.substring(startIndexList.get(i), endIndexList.get(i - 1)));
}
else {
beginIndex = startIndexList.get(i);
endIndex = endIndexList.get(i);
System.out.println(combinedTags.substring(beginIndex, endIndex));
}
}
}
}