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