String ReplaceAll method not working

I use this method to parse plaintext URLs in some HTML and link to them

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;
}

However, HTML does not replace any URLs. The regular expression seems to match the URLs in other regular expression testers. What's happening?

+5
source share
1 answer

Anchor ^means that a regular expression can only match at the beginning of a line. Try to remove it.

In addition, it seems that you mean $0, not $1, since you want the whole match, and not the first capture group, to be (https?|ftp|file).

So 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;
}
+8
source

All Articles