I need a Java port of this https://gist.github.com/jbroadway/2836900, which is basically a simple markdown regex parser in PHP.
I was hoping I could use the backreferenc
The problem is that the backreference values are only honored in the replacement string. As such, the values that are passed to your header()
method are the $0
, $1
and $2
literals and not the captured values.
Since there's no version of replaceAll()
that accepts a lambda expression, I think your best bet would be to use a Matcher object:
String text = "###Heading 3";
Pattern p = Pattern.compile("(#+)(.*)");
Matcher m = p.matcher(text);
StringBuffer out = new StringBuffer();
while(m.find()) {
int level = m.group(1).length();
String title = m.group(2);
m.appendReplacement(out, String.format("<h%s>%s</h%s>", level, title, level));
}
m.appendTail(out);
System.out.println(out.toString());
For the given input, this prints out:
<h3>Heading 3</h3>