/** * 正则表达式匹配两个指定字符串中间的内容 * * @param soap 原字符串 * @param regular 正则匹配字符串 * @return 截取字符串列表 */ public static List<String> getSubUtil(String soap, String regular) { List<String> list = new ArrayList<>(); // 匹配的模式 Pattern pattern = Pattern.compile(regular); Matcher m = pattern.matcher(soap); while (m.find()) { int i = 1; list.add(m.group(i)); i++; } return list; } /** * 返回单个字符串,若匹配到多个的话就返回第一个,方法与getSubUtil一样 * * @param soap 原字符串 * @param regular 正则匹配字符串 * @return 截取字符串列表 */ public static String getSubUtilSimple(String soap, String regular) { // 匹配的模式 Pattern pattern = Pattern.compile(regular); Matcher m = pattern.matcher(soap); while (m.find()) { return m.group(1); } return ""; } public static void main(String[] args) { //测试文本 String test = "<p>hello</p><p><img src=\"http://devcdn.xylink.com/edu-manage-4a336297-9680-40ca-a9c4-36c940f6035b-1573712204410?resourceId=324213124124124131\" style=\"max-width:100%;\"><br></p><p>hello</p><p><img src=\"http://devcdn.xylink.com/edu-manage-4a336297-9680-40ca-a9c4-36c940f6035b-1573712204410?resourceId=324213124124124131\" style=\"max-width:100%;\"><br></p><p>hello</p><p><img src=\"http://devcdn.xylink.com/edu-manage-4a336297-9680-40ca-a9c4-36c940f6035b-1573712204410?resourceId=324213124124124131\" style=\"max-width:100%;\"><br></p><p>hello</p><p><img src=\"http://devcdn.xylink.com/edu-manage-4a336297-9680-40ca-a9c4-36c940f6035b-1573712204410?resourceId=324213124124124131\" style=\"max-width:100%;\"><br></p><p>hello</p><p><img src=\"http://devcdn.xylink.com/edu-manage-4a336297-9680-40ca-a9c4-36c940f6035b-1573712204410?resourceId=324213124124124131\" style=\"max-width:100%;\"><br></p>"; //正则匹配 String rgex = "\\?resourceId=(.*?)\""; String img = "src=\"(.*?)\""; // System.out.println(getSubUtil(test, img)); // System.out.println(CollectionUtils.isEmpty(getSubUtil(test, img))); String imgResourceIdUrl = "http://devcdn.xylink.com/edu-manage-4a336297-9680-40ca-a9c4-36c940f6035b-1573712204410?resorceId=324213124124124131"; String imgUrl = imgResourceIdUrl.substring(0, imgResourceIdUrl.indexOf("?resourceId=")); String resourceId = imgResourceIdUrl.substring(imgResourceIdUrl.indexOf("?resourceId=") + 12); String result = resourceId.replaceAll("resourceId=", ""); System.out.println(imgUrl + "======>" + resourceId); System.out.println(result); }
回去一段字符串中两个指定字符串中间的内容
最新推荐文章于 2021-01-27 11:39:15 发布