Convert a string to another one in java [closed]

随声附和 提交于 2020-01-07 04:20: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.


回答1:


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>");



回答2:


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:


Try:

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

or

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


来源:https://stackoverflow.com/questions/13001259/convert-a-string-to-another-one-in-java

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