I'm using this method to parse out plain text URLs in some HTML and make them links
private String fixLinks(String body) {
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
body = body.replaceAll(regex, "<a href=\"$1\">$1</a>");
Log.d(TAG, body);
return body;
}
No URLs are replaced in the HTML however. The regular expression seems to be matching URLs in other regular expression testers. What's going on?
The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)
replaceAll() The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.
Thank you in advance!!! It might be a trick question; Java strings are immutable so you can't change them "in place".
The ^
anchor means the regex can only match at the start of the string. Try removing it.
Also, it looks like you mean $0
rather than $1
, since you want the entire match and not the first capture group, which is (https?|ftp|file)
.
In summary, the following works for me:
private String fixLinks(String body) {
String regex = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
body = body.replaceAll(regex, "<a href=\"$0\">$0</a>");
Log.d(TAG, body);
return body;
}
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