有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正则表达式将C#正则表达式转换为Java matcher问题

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;
    }

这是一个c#函数,用于获取两个变量之间的字符串。我正在尝试将其转换为java函数。大部分部分已经转换为java代码。 我已成功转换此函数。除本部分外:

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

共 (1) 个答案

  1. # 1 楼答案

    你应该替换

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

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

    关键是,您需要声明一个匹配器,并使用您已经拥有的Pattern中的输入字符串(heap)实例化它

    然后,使用.find(index)执行匹配器,其中index是搜索的起始位置。如果存在匹配项,m.group()包含匹配值