1
public static String ReturnBetween(String heap, String startEx, String endEx, boolean include) {
        int startPos = 0;
        int endPos = heap.length();
        String starts = "";
        String ends = "";

        if (!startEx.equals("^")) {
            Pattern regexStart = Pattern.compile(startEx, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            starts = regexStart.matcher(heap).toString();
            if (starts.equals("")) {
                startPos = -1;
            } else {
                startPos = heap.indexOf(starts);
            }
        }

        if (startPos == -1) {
            return "";
        }

        if (!endEx.equals("$")) {
            Pattern regexEnd = Pattern.compile(endEx, Pattern.CASE_INSENSITIVE | Pattern.DOTALL );
            ends = regexEnd.Match(heap, startPos + starts.length()).toString();
            if (ends.equals("")) {
                endPos = -1;
            } else {
                endPos = heap.indexOf(ends, startPos + starts.length());
            }
        }

        if (endPos == -1) {
            return "";
        }

        if (!include) {
            startPos += starts.length();
        }
        if (include) {
            endPos += ends.length();
        }

        String result = heap.substring(startPos, endPos);
        return result;
    }

This was a c# function for getting a string between two variables i am trying to convert it to java function most the part have been already converted to java code. i have managed to convert this function . except this part :

  ends = regexEnd.Match(heap, startPos + starts.length()).toString();
2
  • Refer to this question: stackoverflow.com/questions/37136376/… to address your issue. Commented Mar 8, 2019 at 11:42
  • @Wiktor Stribiżew Upvoted and thanks about the tip. Commented Mar 13, 2019 at 8:41

1 Answer 1

1

You should replace

ends = regexEnd.Match(heap, startPos + starts.length()).toString();

with

Matcher m = regexEnd.matcher(heap);
if (m.find(startPos + starts.length())) {
  ends =  m.group();
}

The point is that you need to declare a matcher and instantiate it with the input string (heap) from a Pattern that you already have (regexEnd).

Then, you execute the matcher using .find(index) where index is the start position to search from. If there is a match, m.group() contains the match value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.