Some1Else Some1Else - 5 months ago 29
Android Question

Android linkify URLs links non URLs

I want to make web links inside a textview clickable. I used this code

tv.setLinksClickable(true);
tv.setAutoLinkMask(Linkify.WEB_URLS);
Linkify.addLinks(tv, Linkify.WEB_URLS);


which does linkify the web site URLs but also seems to randomly link other text like z.xyz dzo.yzw and others.

How can I tell the linkify to only link URLs? To try and detect links starting with http:// or https:// beginnings I tried this pattern compiling

tv.setLinksClickable(true);
Pattern httpPattern = Pattern.compile("^(http|https)://");
Linkify.addLinks(tv, httpPattern,"");


but that did not work (no links were highlighted). Is that RegEx correct? What should the 3rd parameter to addLinks be?

Thanks for any tips to get this working.

Answer

After much searching and trial and error, this is the solution. Do not use the default Linkiny.WEB_URLS. Use a custom regex pattern that looks for links. I used the following (et is an EditText).

et.setLinksClickable(true);
Pattern httpPattern = Pattern.compile("[a-z]+:\\/\\/[^ \\n]*");
Linkify.addLinks(et, httpPattern,"");

That will only linkify URLs and not other strings with 2 words separated by a full stop as Linkify.WEB_URLS can do.

If that regex is not good enough for your needs see the following link for heaps of tested alternatives that handle more complex cases https://mathiasbynens.be/demo/url-regex

Hope that helps someone else with the same issue.