简体   繁体   中英

String ReplaceAll method not working

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM