az fav
az fav

Reputation: 106

Converting C# Regular Expression To Java matcher issue

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();

Upvotes: 1

Views: 99

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

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.

Upvotes: 1

Related Questions