Skip to content

Instantly share code, notes, and snippets.

@cbedoy
Created October 17, 2017 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbedoy/e52abced9cbc8a3612e52c9af074a5cd to your computer and use it in GitHub Desktop.
Save cbedoy/e52abced9cbc8a3612e52c9af074a5cd to your computer and use it in GitHub Desktop.
Example extract url from message or text :)
public String extractURL(String input)
{
if (input.length() == 0)
return null;
int[] positionsOfUrl = positionsOfUrl(input);
return input.substring(positionsOfUrl[0], positionsOfUrl[1]);
}
public int[] positionsOfUrl(String input)
{
LinkExtractor linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL, LinkType.WWW, LinkType.EMAIL))
.build();
Iterable<LinkSpan> links = linkExtractor.extractLinks(input);
if (links.iterator().hasNext())
{
LinkSpan link = links.iterator().next();
link.getType(); // LinkType.URL
link.getBeginIndex(); // 17
link.getEndIndex();
return new int[]{link.getBeginIndex(), link.getEndIndex()};
}
else
return new int[]{0, 0};
}
//Example from unit testing
@Test
public void shouldExtractExpectedURL() throws Exception {
String extractURL = CBUtils.getInstance().extractURL("Hey there's a url: https://www.spotify.com/mx/");
assertEquals("https://www.spotify.com/mx/", extractURL);
}
@Test
public void shouldReturnEmptyIfIsNoExistURL() throws Exception {
String extractURL = CBUtils.getInstance().extractURL("Hey there's no a URL");
assertEquals("", extractURL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment