java文本获取中间内容

 

使用正则方式提取文本中间内容

获取文本中间(单次)

参数1:文本

参数2:文本前

参数3:文本后

返回一个String

 public static String getSubString(String text, String left, String right) {

        String result = "";

        int zLen;

        if (left == null || left.isEmpty()) {

            zLen = 0;

        } else {

            zLen = text.indexOf(left);

            if (zLen > -1) {

                zLen += left.length();

            } else {

                zLen = 0;

            }

        }

        int yLen = text.indexOf(right, zLen);

        if (yLen < 0 || right == null || right.isEmpty()) {

            yLen = text.length();

        }

        result = text.substring(zLen, yLen);

        return result;

    }

 

批量获取文本中间

参数1:文本

参数2:文本前

参数3:文本后

返回一个String列表

//    批量获取中间文本
    public static List<String> GetSubTextList(String sourceText,String frontIdentificationText,
                                                                 String subsequentIdentificationText) {
        ArrayList<String> list = new ArrayList<>();

        Pattern pattern = Pattern.compile(escapeMetacharacter(frontIdentificationText) + "([\\s\\S]*?)" +
                escapeMetacharacter(subsequentIdentificationText), Pattern.DOTALL);
        Matcher m = pattern.matcher(sourceText);

        while (m.find()) {
            String group = m.group(1);
            list.add(group);
        }

        return list;
    }

//    正则替换
    public static String escapeMetacharacter(String text) {
        return text.replace("?","\\?").replace("*", "\\*").replace("+", "\\+")
                .replace("[", "\\[").replace("]", "\\]").replace("(", "\\(")
                .replace(")", "\\)").replace("{", "\\{").replace("}", "\\}");
    }

 

posted @ 2023-03-19 18:29  Hello霖  阅读(134)  评论(0)    收藏  举报