Skip to content

README: Update example to use a loop #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading