Suppose I have a String message:
“you should upload file.zip to http://google.com/extremelylonglink.zip, not https://stackoverflow.com/extremelylonglink.zip. try again.”
I want a function to return to String newmessage:
“you should upload file.zip to [shorted version of first link], not [shortened version of second link]. try again.”
I already have the code for the URL shortener, and here is my URL detection code that replaces the first URL in a message:
if(message.contains("http://") || message.contains("https://")) {
String regex = "(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";
Matcher m = Pattern.compile(regex).matcher(message);
if (m.find()) {
String url = m.group();
String shorted = null;
try {
shorted = Shortener.GetShortedISGD(url);
} catch (IOException e1) {
// TODO Auto-generated catch block
}
}
String intercepted = message.replace(url, shorted);
e.setMessage(intercepted);
}
How would I go about replacing ALL of them?
(I’m using the Bukkit API for a lot of this, so a lot of the functions aren’t in Java).
I’m thinking of splitting up message into an array of words, and then evaluating if each word would be a URL, except that would be kinda not optimized.
Use
appendReplacementandappendTail. See example in the Java tutorial and another example closer to what you are trying to do.