X

Geertjan's Blog

  • June 21, 2015

Handy Parsing Utilities for Markdown

Geertjan Wielenga
Product Manager

Kendo UI comes with Markdown documents that I'm working with to provide content for the code completion box:

Initially I was using some kind of Markdown parsing library, but then I realized hey why not simply use pattern matching instead: 

public class DataLoader {
private static final Set<DemoDataItem> items = new HashSet<DemoDataItem>();
public static Set<DemoDataItem> getData(List<File> files) {
items.clear();
for (File file : files) {
try {
String asText = FileUtil.toFileObject(file).asText();
String pattern = "title: [A-Za-z]+";
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(asText);
if (matcher.find()) {
String formattedText = matcher.group().replace("title: ", "kendo");
items.add(new DemoDataItem(formattedText, null, escapeHTML(asText), null));
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
return items;
}
//http://stackoverflow.com/questions/9580684/how-to-retrieve-title-of-a-html-with-the-help-of-htmleditorkit
public static String escapeHTML(String s) {
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("&#");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
String addBreak = out.toString().replace("\n", "<br />\n");;
return addBreak;
}
}

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.