检测并缩短字符串中的所有URL [英] Detect and shorten ALL urls in string

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

问题描述

假设我有一个字符串消息:

Suppose I have a String message:

你应该将file.zip上传到 http://google.com/extremelylonglink.zip ,而不是 https://stackoverflow.com/ verylonglink.zip 。再试一次。

"you should upload file.zip to http://google.com/extremelylonglink.zip, not https://stackoverflow.com/extremelylonglink.zip. try again."

我想要一个函数返回String newmessage:

I want a function to return to String newmessage:

你应该将file.zip上传到[第一个链接的缩短版本],而不是[缩短版本的第二个链接]。再试一次。

"you should upload file.zip to [shorted version of first link], not [shortened version of second link]. try again."

我已经拥有URL缩短器的代码,这是我的URL检测代码,它替换了邮件中的第一个URL:

I already have the code for the URL shortener, and here is my URL detection code that replaces the first URL in a message:

        if(message.contains("http://") || message.contains("https://")) {
            String regex = "(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»""‘’]))";
            Matcher m = Pattern.compile(regex).matcher(message);
            if (m.find()) {
                String url = m.group();
                    String shorted = null;      
                        try {       
                             shorted = Shortener.GetShortedISGD(url);                                                                           
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                        }
                    }
                    String intercepted = message.replace(url, shorted);
                    e.setMessage(intercepted);
        }

我如何更换所有这些?
(我正在使用Bukkit API,所以很多函数都不是Java)。

How would I go about replacing ALL of them? (I'm using the Bukkit API for a lot of this, so a lot of the functions aren't in Java).

我在想将消息拆分成一个单词数组,然后评估每个单词是否都是一个URL,除非有点没有优化。

I'm thinking of splitting up message into an array of words, and then evaluating if each word would be a URL, except that would be kinda not optimized.

推荐答案

使用 appendReplacement appendTail 。请参阅Java教程中的示例另一个示例更接近您要做的事情。

Use appendReplacement and appendTail. See example in the Java tutorial and another example closer to what you are trying to do.

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

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