java清除所有微博短链接 Java问题通用解决代码


java实现微博短链接清除,利用正则,目前只支持微博短链接格式为"http://域名/字母或数字8位以内"的链接格式,现在基本通用
如果链接有多个,返回结果中会有多出的空格,请注意!
 
实现代码:
 
 
1.测试版

      public static void main(String[] args) {
            // System.out.println(testFilter("刚在#微操盘#卖出的这支600111 包钢稀土 又挣钱了!有木有!人品爆发了有木有! http://t.cn/zlrQS3L",
            // "微操盘"));
 
            String text = "#转播越多,http://url.cn/79H8ORhttp://url.cn/79H8OR收获越http://t.cn/79H8OR多#予人玫瑰,手留余香。“一键转播”精彩内容至腾讯微博,分享给好友,还可淘Q币,赢公仔!转播越多,机会越多~拿起鼠标疯狂转起来,转出自己的style!http://url.cn/79H8ORqqwweerrtt";
            // String regex = "http://t.cn/\w+";
            text = text.replace("http://", " http://");
            System.out.println(text);
            // /后面字符在这[A-Za-z0-9_]之内,都会被匹配
            // String regex = "(http://(url|t).cn/\w+)";
 
            // /后面字符在这[A-Za-z0-9_]之内,只会匹配0~7次
            String regex = "(http://(url|t).cn/\w{0,7})";
            text = text.replaceAll(regex, "");
            System.out.println(text);
 
            text = WebUtil.filterSpecialChar(text);
            System.out.println(text);
      }

 
2.正式版

      /**
       * 清除所有微博短链接
       *
       * @param s
       *            文本
       * @return 清除所有链接后的文本,返回内容中会多一些空格,请注意
       */
      public static String clearWeiboShortUrl(String s) {
            // 如果要清除的链接有多个的话,还需要清除为了清除多个链接而补充的空格,不然内容中会多出空格来
            if (null != s) {
                  // 各大微博链接
                  // http://163.fm/XY9AT9z
                  // http://url.hexun.com/1JX44
                  // http://yicai.net/WMK8r
                  // http://t.cn/79H8OR
                  // http://t.itc.cn/79H8OR
                  // http://url.cn/79H8OR
 
                  // Matcher matcher =
                  // Pattern.compile("(http://(url|t).cn/)").matcher(s);
                  // 各大微博链接不一致,修改域名任意
                  Matcher matcher = Pattern.compile("(http://[\w.]+/)").matcher(s);
                  int count = 0;
                  while (matcher.find()) {
                        count++;
                        // System.out.println(matcher.group());
                  }
                  // int count =
                  // Pattern.compile("(http://(url|t).cn)").matcher(s).groupCount();
                  if (count > 0) {
                        if (count > 1) {
                              s = s.replace("http://", " http://");
                        }
                        // /后面字符在这[A-Za-z0-9_]之内,都会被匹配
                        // String regex = "(http://(url|t).cn/\w+)";
                        // /后面字符在这[A-Za-z0-9_]之内,只会匹配0~10次
                        // String regex = "(http://(url|t).cn/\w{0,10})";
                        // 域名任意,/后面字符在这[A-Za-z0-9_]之内,只会匹配0~10次
                        String regex = "(http://[\w.]+/\w{0,10})";
                        s = s.replaceAll(regex, "");
                  }
            }
            return s;
      }

原文地址:https://www.cnblogs.com/svennee/p/4082823.html