【问题标题】:Detect and shorten ALL urls in string检测并缩短字符串中的所有 url
【发布时间】:2012-10-29 00:08:15
【问题描述】:

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

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

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

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

我已经有了 URL 缩短器的代码,这是我的 URL 检测代码,用于替换消息中的第一个 URL:

        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 语言)。

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

【问题讨论】:

    标签: java regex string url


    【解决方案1】:

    使用appendReplacementappendTail。请参阅 Java 教程中的 exampleanother example 更接近您想要做的事情。

    【讨论】:

    • 试试吧,让我知道!但是,这里的another example 更接近于您使用appendReplacementappendTail 尝试做的事情。
    • 对于可能无限数量的道具,我该怎么做?
    • 在那个例子中,props 只是一个替换字典。您在这里不需要或不想要它,因为您的 GetShortedISGD 提供了替换价值。每次通过while 循环,您只需附加Shortener.GetShortedISGD(m.group(1))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2011-08-08
    • 2017-11-11
    • 2019-03-21
    • 2014-05-01
    • 2011-04-28
    • 2019-10-04
    相关资源
    最近更新 更多