forked from ucsd-cse15l-w22/markdown-parse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkdownParse.java
More file actions
72 lines (61 loc) · 2.44 KB
/
MarkdownParse.java
File metadata and controls
72 lines (61 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
public class MarkdownParse {
public static ArrayList<String> getLinks(String markdown) {
ArrayList<String> toReturn = new ArrayList<>();
// find the next [, then find the ], then find the (, then take up to
// the next )
int currentIndex = 0;
int lastClosedParen = markdown.lastIndexOf(")");
while(currentIndex < markdown.length()) {
int nextOpenBracket = markdown.indexOf("[", currentIndex);
boolean isImage = false;
if (markdown.indexOf("!", nextOpenBracket-1) == nextOpenBracket - 1) {
isImage = true;
}
if (nextOpenBracket == 0){
isImage = false;
}
int nextCloseBracket = markdown.indexOf("]", nextOpenBracket);
int openParen = markdown.indexOf("(", currentIndex);
int closeParen = markdown.indexOf(")", openParen);
if(nextOpenBracket == -1 || nextCloseBracket == -1 || openParen == -1 || closeParen == -1) {
break;
}
if (openParen - nextCloseBracket > 2) {
currentIndex = markdown.indexOf("[", currentIndex + 1);
if (currentIndex == lastClosedParen) {
break;
} else if (currentIndex < 0) {
break;
}
continue;
}
if(nextOpenBracket != 0 && markdown.substring(nextOpenBracket-1, nextOpenBracket).equals("!")){
currentIndex = closeParen + 1;
continue;
}
//System.out.println(markdown.substring(nextOpenBracket, nextCloseBracket));
//if(markdown.substring(nextOpenBracket + 1, nextCloseBracket).equals("")){
// continue;
//}
if (isImage == false) {
toReturn.add(markdown.substring(openParen + 1, closeParen));
}
if (closeParen > currentIndex){
currentIndex = closeParen + 1;
} else {
break;
}
}
return toReturn;
}
public static void main(String[] args) throws IOException {
Path fileName = Path.of(args[0]);
String contents = Files.readString(fileName);
ArrayList<String> links = getLinks(contents);
System.out.println(links);
}
}