Pass Java backreference to method parameter

后端 未结 1 1447
有刺的猬
有刺的猬 2021-01-24 03:43

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

相关标签:
1条回答
  • 2021-01-24 04:22

    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>
    
    0 讨论(0)
提交回复
热议问题