int (@NotNull String startSymbol, @NotNull String endSymbol, @NotNull String text, int afterStartIdx) { if (afterStartIdx < 0) return -1; int totalNumStarts = 1; int lookFrom = afterStartIdx; while (totalNumStarts > 0) { --totalNumStarts; int nextEndIdx = text.indexOf(endSymbol, lookFrom); if (nextEndIdx == -1) return -1; final int numStarts = getOccurrenceCount(text, lookFrom, nextEndIdx, startSymbol); if (numStarts > 0) { totalNumStarts += numStarts; } lookFrom = nextEndIdx + endSymbol.length(); if (totalNumStarts == 0) return nextEndIdx; } return -1; }