java replace substring between two strings
/** * * @param firstString the string where you wan * @param lastString * @param occurence * @param replace the string between the firstString and lastString * @param stringBody this is the whole string * @return */ public static String replaceStringBtwn(String stringBody, int occurence, String firstString, String lastString, String replace) { StringBuilder firstPart = new StringBuilder(); StringBuilder lastPart = new StringBuilder(); int partPortion = 1; int occurenceEncountered = 1; for (String elem : stringBody.split("\n")) { if (partPortion == 1 && !elem.contains(firstString)) { firstPart.append(elem + "\n"); continue; } if (partPortion == 2) { lastPart.append(elem + "-\n"); continue; } if (elem.contains(firstString)) { if (occurence == occurenceEncountered) { firstPart.append(firstString); firstPart.append(replace); firstPart.append(lastString); firstPart.append("\n"); partPortion = 2; occurence = occurence + 1; } occurenceEncountered = occurenceEncountered + 1; continue; } } return firstPart.append(lastPart).toString(); }