开发者

Help with regex to detect urls in a string

开发者 https://www.devze.com 2023-02-02 02:29 出处:网络
Hi guys i found this regex to detect urls in a string and wraps them inside thetag public static String detectUrls(String text) {

Hi guys i found this regex to detect urls in a string and wraps them inside the tag

public static String detectUrls(String text) {
    String newText = text
            .replaceAll("(?<!http://)www\\.[\\w/%.\\-?&=]+", "http://$0")
            .replaceAll("(?:https?|ftps?|http?)://[\\w/%.\\-?&=]+",
                    开发者_如何学运维"<a href='$0'>$0</a>");
    return newText;
}

but this regex doesn't work with the following pattern:

https://www.myserver.com

so please advise.


This line:

.replaceAll("(?<!http://)www\\.[\\w/%.\\-?&=]+", "http://$0")

Changes https://www.myserver.com to https://http://www.myserver.com

It does exactly has you've instructed it. You need to add https, and probably ftps? to the lookbehind as well.

You may also ignore the protocol:

.replaceAll("(?<!://)www\\.", "http://$0")


I think that this is maybe you want:

public static String detectLinks(String text) {
        String newText = text.replaceAll(
                "(?<!(http|https|ftps)://)www\\.[\\w/%.\\-?&=]+", "$0")
                .replaceAll("(?<!://)www\\.", "http://$0").replaceAll(
                        "(?:https?|ftps?|http?)://[\\w/%.\\-?&=+#]+",
                        "<a href='$0'>$0</a>")

        return newText;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消