private int findClosestIndexOf(String context, int oldIndex, String content) {

    Matcher matcher = Pattern.compile(Pattern.quote(context)).matcher(content);
    int index = 0;

    while (matcher.find()) {
      if (Math.abs(oldIndex - matcher.start()) < (Math.abs(oldIndex - index))) {
        index = matcher.start();
      }
    }

    return index;
  }
  private TextConstraint exactMatch(String primaryContent, TextConstraint originalConstraint)
      throws NoMatchFoundException {

    // find the text before the annotation
    // int startPos = primaryContent.indexOf(this.beforeContext);
    int startPos =
        findClosestIndexOf(
            this.beforeContext,
            originalConstraint.getStartPos() - this.beforeContext.length(),
            primaryContent);

    startPos += this.beforeContext.length();

    // find text after annotation
    // int endPos = primaryContent.indexOf(this.afterContext);
    int endPos =
        findClosestIndexOf(this.afterContext, originalConstraint.getEndPos(), this.totalSelection);

    if (endPos < 0 || startPos < 0) {
      // search through the selected content

      int positionTotal = 0;
      if (this.beginSel.length() > 0 && this.endSel.length() > 0) {
        int originalPosTotal =
            (originalConstraint.getStartPos()
                + (originalConstraint.getEndPos() - this.endSel.length()));

        // search beginning source selection, then end
        // selection, respectively
        int beginTotal =
            findClosestIndexOf(this.beginSel, originalConstraint.getStartPos(), primaryContent);

        int afterTotal =
            findClosestIndexOf(
                this.endSel,
                (originalConstraint.getEndPos() - this.endSel.length()),
                primaryContent);

        positionTotal = beginTotal + afterTotal;

        if (Math.abs(positionTotal - originalPosTotal) > 5) {
          return null;
        }

      } else {
        // search through total selection
        positionTotal =
            findClosestIndexOf(
                this.totalSelection, originalConstraint.getStartPos(), primaryContent);
        if (positionTotal < 0) return null;
      }
    }

    return new TextConstraint(startPos, endPos);
  }