Files

112 lines
3.5 KiB
Java

/**
* MIT License
*
* Copyright (c) 2021 Exercism
* Copyright (c) 2026 Networked Embedded Systems, University of Duisburg-Essen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
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("(<li>).*") && !theLine.matches("(<h).*") && !theLine.matches("(<p>).*")
&& !activeList) {
activeList = true;
result = result + "<ul>";
result = result + theLine;
}
else if (!theLine.matches("(<li>).*") && activeList) {
activeList = false;
result = result + "</ul>";
result = result + theLine;
} else {
result = result + theLine;
}
}
if (activeList) {
result = result + "</ul>";
}
return result;
}
private String parseHeader(String markdown) {
int count = 0;
for (int i = 0; i < markdown.length() && markdown.charAt(i) == '#'; i++) {
count++;
}
if (count > 6) {
return "<p>" + markdown + "</p>";
}
if (count == 0) {
return null;
}
return "<h" + Integer.toString(count) + ">" + markdown.substring(count + 1) + "</h" + Integer.toString(count)
+ ">";
}
private String parseListItem(String markdown) {
if (markdown.startsWith("*")) {
String skipAsterisk = markdown.substring(2);
String listItemString = parseSomeSymbols(skipAsterisk);
return "<li>" + listItemString + "</li>";
}
return null;
}
private String parseParagraph(String markdown) {
return "<p>" + parseSomeSymbols(markdown) + "</p>";
}
private String parseSomeSymbols(String markdown) {
String lookingFor = "__(.+)__";
String update = "<strong>$1</strong>";
String workingOn = markdown.replaceAll(lookingFor, update);
lookingFor = "_(.+)_";
update = "<em>$1</em>";
return workingOn.replaceAll(lookingFor, update);
}
}