5

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?

asked Nov 29, 2011 at 20:34
2
  • 1
    Can you post an example snippet of HTML? Are you sure the links are all at the beginning of the line? I'd add a \s* after the ^ to allow for whitespace. Commented Nov 29, 2011 at 20:37
  • 1
    +1 for asking a question about replaceAll that wasn't confusion about it expecting a regex :) Commented Nov 29, 2011 at 20:44

1 Answer 1

9

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;
}
answered Nov 29, 2011 at 20:42
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. You just saved me from jumping off a bridge.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.