愿 每 一 |

Hello霖

园龄:4年1个月粉丝:4关注:0

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("}", "\\}");
    }

 

本文作者:Hello

本文链接:https://www.cnblogs.com/Hello233/p/17233890.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Hello霖  阅读(108)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起