问题
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 backreferences, but I can't make it work.
At the moment I'm not using a HashMap
, I've got 2 JavaFX TextArea
s where I'll get and set the text via a ChangeListener
.
{ //...
htmlTextArea.setText(markdownTextArea.getText()
.replaceAll("(#+)(.*)", header("$0", "$1", "$2"));
}
private String header(String text, String char, String content) {
return String.format("<h%s>$2</h%s>", char.length(), char.length());
The backreference on $2 works, only if returned, but other backreferences don't. char.length()
is always 2 since it's treated as $2
and not as a backreference.
Id like to think of a solution where I can keep this style and don't need to handle this separately.
回答1:
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>
来源:https://stackoverflow.com/questions/43269070/pass-java-backreference-to-method-parameter