There is one more possible solution. The second if condition shown below-
if (trimLine.endsWith(this.pattern1)) {
if (!trimLine.equals(this.pattern1)) {
//code goes here
}
}
can be changed to - if ((prefixCounter == 1) &&
!trimLine.equals(this.pattern1)) {}
So that the second condition will be tested only for closing pattern and
not for opening.