Pass Java backreference to method parameter

泪湿孤枕 提交于 2021-01-20 09:42:16

问题


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 TextAreas 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!