Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String ReplaceAll method not working

Tags:

java

regex

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?

like image 541
SeanPONeil Avatar asked Nov 29 '11 20:11

SeanPONeil


People also ask

What is the difference between Replace () and replaceAll ()?

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)

What do the replaceAll () do in Java?

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.

Is string replace inplace in Java?

Thank you in advance!!! It might be a trick question; Java strings are immutable so you can't change them "in place".


1 Answers

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;
}
like image 114
NPE Avatar answered Oct 03 '22 23:10

NPE