Usually, this is either done with a regular expression or with indexOf
and substring
.
With a regular expression, this can be done like that:
// This is using a VERY simplified regular expression
String str = "internet address : http://test.com Click this!";
Pattern pattern = Pattern.compile("[http:|https:]+\\/\\/[\\w.]*");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(0));
}
You can read here why it's simplified: https://mathiasbynens.be/demo/url-regex - tl;dr: the problem with URLs is they can have so many different patterns which are valid.
With split, there would be a way utilizing the URL class of Java:
String[] split = str.split(" ");
for (String value : split) {
try {
URL uri = new URL(value);
System.out.println(value);
} catch (MalformedURLException e) {
// no valid url
}
}
You can check their validation in the OpenJDK source here.