从字符串中检测并提取url? [英] Detect and extract url from a string?

查看:144
本文介绍了从字符串中检测并提取url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题,但我不明白。
我想检测字符串中的url并用缩短的字符串替换它们。

This is a easy question,but I just don't get it. I want to detect url in a string and replace them with a shorten one.

我从stackoverflow中找到了这个表达式,但结果只是 http

I found this expression from stackoverflow,But the result is just http

Pattern p = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]",Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        boolean result = m.find();
        while (result) {
            for (int i = 1; i <= m.groupCount(); i++) {
                String url=m.group(i);
                str = str.replace(url, shorten(url));
            }
            result = m.find();
        }
        return html;

还有更好的主意吗?

推荐答案

m.group(1)为您提供第一个匹配组,即第一个捕获括号。这是(https?| ftp |文件)

m.group(1) gives you the first matching group, that is to say the first capturing parenthesis. Here it's (https?|ftp|file)

你应该试着看看m中是否有东西。 group(0),或用括号括起所有模式并再次使用m.group(1)。

You should try to see if there is something in m.group(0), or surround all your pattern with parenthesis and use m.group(1) again.

你需要重复你的find函数来匹配下一个和使用新的组数组。

You need to repeat your find function to match the next one and use the new group array.

这篇关于从字符串中检测并提取url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆