1

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.

Ali Taha Ali Mahboub
  • 3,271
  • 6
  • 26
  • 25
  • Duplicate : http://stackoverflow.com/questions/4519134/issues-with-my-regex-to-detect-urls-in-a-string/4519415#4519415 – Toto Jan 04 '11 at 09:27

2 Answers2

2

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")
Kobi
  • 135,331
  • 41
  • 252
  • 292
1

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;
    }
Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498