Created
October 17, 2017 06:04
-
-
Save cbedoy/e52abced9cbc8a3612e52c9af074a5cd to your computer and use it in GitHub Desktop.
Example extract url from message or text :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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