Convert a string to another one in java [closed]

2019-08-22 16:12发布

How do I convert #title to <h1>title</h1> in java? I'm trying to create an algorithm to convert markdown format to html format.

3条回答
SAY GOODBYE
2楼-- · 2019-08-22 16:30

Say that you used a hash at the beginning and the end of the marked word(s), you could use a method like this which would do all of them in a String.

private String replaceTitles(String entry) {
    Matcher m = Pattern.compile("#(.*?)#").matcher(entry);
    StringBuffer buf = new StringBuffer(entry.length());
    while (m.find()) {

        String text = m.group(1);
        StringBuffer b = new StringBuffer();
        b.append("<h1>").append(text).append("</h1>");

        m.appendReplacement(buf, Matcher.quoteReplacement(b.toString()));
    }
    m.appendTail(buf);
    return buf.toString();
}

If you called

replaceTitles("#My Title One!# non title text, #One more#")

it would return

"<h1>My Title One!</h1> non title text, <h1>One more</h1>"
查看更多
手持菜刀,她持情操
3楼-- · 2019-08-22 16:39

Try:

  String inString = "#title";
  String outString = "<h1>"+inString.substring(1)+"</h1>";

or

  String outString = "<h1>"+"#title".substring(1)+"</h1>";
查看更多
欢心
4楼-- · 2019-08-22 16:41

If you want to create markdown algorithm look for regular expression.

String noHtml = "#title1";
String html = noHtml.replaceAll("#(.+)", "<h1>$1</h1>");

answer to comment - more about character classes here:

String noHtml = "#title1";
String html = noHtml.replaceAll("#([a-zA-Z]+)", "<h1>$1</h1>");
查看更多
登录 后发表回答