class Markdown {
String parse(String markdown) {
String[] lines = markdown.split("\n");
String result = "";
boolean activeList = false;
for (int i = 0; i < lines.length; i++) {
String theLine = parseHeader(lines[i]);
if (theLine == null) {
theLine = parseListItem(lines[i]);
}
if (theLine == null)
{
theLine = parseParagraph(lines[i]);
}
if (theLine.matches("(
).*") && !theLine.matches("().*") && !activeList) {
activeList = true;
result = result + "";
result = result + theLine;
}
else if (!theLine.matches("(- ).*") && activeList) {
activeList = false;
result = result + "
";
result = result + theLine;
} else {
result = result + theLine;
}
}
if (activeList) {
result = result + "";
}
return result;
}
private String parseHeader(String markdown) {
int count = 0;
for (int i = 0; i < markdown.length() && markdown.charAt(i) == '#'; i++)
{
count++;
}
if (count == 0) { return null; }
return "" + markdown.substring(count + 1) + "";
}
private String parseListItem(String markdown) {
if (markdown.startsWith("*")) {
String skipAsterisk = markdown.substring(2);
String listItemString = parseSomeSymbols(skipAsterisk);
return "" + listItemString + "";
}
return null;
}
private String parseParagraph(String markdown) {
return "" + parseSomeSymbols(markdown) + "
";
}
private String parseSomeSymbols(String markdown) {
String lookingFor = "__(.+)__";
String update = "$1";
String workingOn = markdown.replaceAll(lookingFor, update);
lookingFor = "_(.+)_";
update = "$1";
return workingOn.replaceAll(lookingFor, update);
}
}