/** * 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("(
  • ).*") && !theLine.matches("().*") && !activeList) { activeList = true; 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 > 6) { return "

    " + markdown + "

    "; } 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); } }