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.
Here'a s pattern that corresponds to RFC 3986 (URL standard):
public static final Pattern URL_PATTERN = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
from: https://stackoverflow.com/a/5713866/2980992.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With