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

查看:22
本文介绍了从字符串中检测并提取 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|file)

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.

您需要重复查找函数以匹配下一个并使用新的组数组.

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

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

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