Can anyone advise? And how does the replace all method works?
message = message.replaceAll("(?:https?|http?)://[\\w/%.\\-?&=!#]+",
"<a href='$0' target='_blank'>$0</a>");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should be taken this each step at a time to understand:
|-> means OR so it means matches either https or http?-> (only here) means optional elements, “s” from https is optional or “p” from http is optional too. What you probably meant is to do : “(https)?|(http)?“, make each optional. But this is still wrong, because you then could match a String like this one: “://someLink” – which does not make sense.I suppose you want to match https OR http, thus your regex here needs to changed to :
?:-> it defines a non-capturing group (it means it will be matched but not present in the output – not captured in the result), this is something related to regex groups.()-> mean that this is a groupand as matter of fact this is the second group (the first is the whole match itself)
This regex “
://[\\w/%.\\-?&=!#]+” has been explained above pretty good I think.Here is the “magic” that happens here: “
$0“, this is called a backreference to a matching group. So inside your message String, the result that you have matched with the regex:will be replaced with this:
where
$0is actually the thing that was found with the first regex.Here is an example actually: