forked from nidhidhamnani/markdown-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkdownParse.java
More file actions
57 lines (48 loc) · 2.21 KB
/
MarkdownParse.java
File metadata and controls
57 lines (48 loc) · 2.21 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
//https://howtodoinjava.com/java/io/java-read-file-to-string-examples/
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import javax.script.ScriptContext;
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 read link upto next )
// unsafe url characters: "{", "}", "|", "\", "^", "~", "[", "]", " ", and "`"
// if one of these characters exists before the close parens, we assume the url is overs
int currentIndex = 0;
while(currentIndex < markdown.length()) {
int openBracket = markdown.indexOf("[", currentIndex);
int closeBracket = markdown.indexOf("]", openBracket);
int openParen = markdown.indexOf("(", closeBracket);
int closeParen = markdown.indexOf(")", openParen);
if(closeBracket == -1 || openBracket == -1 || closeParen == -1|| openParen == -1)
break;
if(openParen - closeBracket == 1) //only add if the openParen and closeBracket are adjacent
{
try
{
if (!(markdown.substring(openBracket - 1, openBracket).equals("!"))) //only add it if it's not an image
{
toReturn.add(markdown.substring(openParen + 1, closeParen));
}
}
//if open bracket is at index 0, then it's a link and not an image so run as normal.
catch(IndexOutOfBoundsException e)
{
toReturn.add(markdown.substring(openParen + 1, closeParen));
}
}
currentIndex = closeParen + 1;
}
return toReturn;
}
public static void main(String[] args) throws IOException {
Path fileName = Path.of(args[0]);
System.out.println(Files.readString(fileName));
String content = Files.readString(fileName);
ArrayList<String> links = getLinks(content);
System.out.println(links);
}
}