Skip to content

Commit

Permalink
Merge pull request #44 from robinst/readme-example
Browse files Browse the repository at this point in the history
README: Update example to use a loop
  • Loading branch information
robinst authored Nov 19, 2024
2 parents 638568c + f5aa504 commit 0960710
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,17 @@ Extracting links:
```java
import org.nibor.autolink.*;

String input = "wow, so example: http://test.com";
LinkExtractor linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL, LinkType.WWW, LinkType.EMAIL))
var input = "two links: https://test.com and https://example.com";
var linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL)) // limit to URLs
.build();
Iterable<LinkSpan> links = linkExtractor.extractLinks(input);
LinkSpan link = links.iterator().next();
link.getType(); // LinkType.URL
link.getBeginIndex(); // 17
link.getEndIndex(); // 32
input.substring(link.getBeginIndex(), link.getEndIndex()); // "http://test.com"
var links = new ArrayList<>();
for (var span : linkExtractor.extractLinks(input)) {
var link = input.substring(span.getBeginIndex(), span.getEndIndex());
links.add(link);
}

links; // List.of("https://test.com", "https://example.com")
```

Note that by default all supported types of links are extracted. If
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/org/nibor/autolink/UsageExampleTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import org.junit.Test;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Stream;

import static org.junit.Assert.assertEquals;

Expand Down Expand Up @@ -35,6 +38,21 @@ public void linkify() {
assertEquals("wow <a href=\"http://test.com\">http://test.com</a> such linked", sb.toString());
}

@Test
public void extractLinks() {
var input = "hey https://test.com and https://example.com";
var linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL))
.build();
var links = new ArrayList<>();
for (var linkSpan : linkExtractor.extractLinks(input)) {
var link = input.substring(linkSpan.getBeginIndex(), linkSpan.getEndIndex());
links.add(link);
}

assertEquals(List.of("https://test.com", "https://example.com"), links);
}

// Mocked here to not have to depend on owasp-java-encoder in tests
private static class Encode {
public static String forHtmlAttribute(String text) {
Expand Down

0 comments on commit 0960710

Please sign in to comment.