lots of exercises in java... from https://github.com/exercism/java

Markdown.java 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. class Markdown {
  2. String parse(String markdown) {
  3. String[] lines = markdown.split("\n");
  4. String result = "";
  5. boolean activeList = false;
  6. for (int i = 0; i < lines.length; i++) {
  7. String theLine = parseHeader(lines[i]);
  8. if (theLine == null) {
  9. theLine = parseListItem(lines[i]);
  10. }
  11. if (theLine == null)
  12. {
  13. theLine = parseParagraph(lines[i]);
  14. }
  15. if (theLine.matches("(<li>).*") && !theLine.matches("(<h).*") && !theLine.matches("(<p>).*") && !activeList) {
  16. activeList = true;
  17. result = result + "<ul>";
  18. result = result + theLine;
  19. }
  20. else if (!theLine.matches("(<li>).*") && activeList) {
  21. activeList = false;
  22. result = result + "</ul>";
  23. result = result + theLine;
  24. } else {
  25. result = result + theLine;
  26. }
  27. }
  28. if (activeList) {
  29. result = result + "</ul>";
  30. }
  31. return result;
  32. }
  33. private String parseHeader(String markdown) {
  34. int count = 0;
  35. for (int i = 0; i < markdown.length() && markdown.charAt(i) == '#'; i++)
  36. {
  37. count++;
  38. }
  39. if (count == 0) { return null; }
  40. return "<h" + Integer.toString(count) + ">" + markdown.substring(count + 1) + "</h" + Integer.toString(count)+ ">";
  41. }
  42. private String parseListItem(String markdown) {
  43. if (markdown.startsWith("*")) {
  44. String skipAsterisk = markdown.substring(2);
  45. String listItemString = parseSomeSymbols(skipAsterisk);
  46. return "<li>" + listItemString + "</li>";
  47. }
  48. return null;
  49. }
  50. private String parseParagraph(String markdown) {
  51. return "<p>" + parseSomeSymbols(markdown) + "</p>";
  52. }
  53. private String parseSomeSymbols(String markdown) {
  54. String lookingFor = "__(.+)__";
  55. String update = "<strong>$1</strong>";
  56. String workingOn = markdown.replaceAll(lookingFor, update);
  57. lookingFor = "_(.+)_";
  58. update = "<em>$1</em>";
  59. return workingOn.replaceAll(lookingFor, update);
  60. }
  61. }