2012-10-21 35 views
0

如何將#title轉換爲java中的<h1>title</h1>?我試圖創建一個算法來將markdown格式轉換爲html格式。在java中將字符串轉換爲另一個

+0

那你試試? Q不清楚... – Frank

+2

您可以閱讀http://code.google.com/p/markdownj/的代碼 – Augusto

+0

爲什麼不使用一些現有的Markdown解析器? – Crozin

回答

6

如果你想創建降價算法尋正則表達式。

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

答案評論 - 更多字符類here

String noHtml = "#title1"; 
String html = noHtml.replaceAll("#([a-zA-Z]+)", "<h1>$1</h1>"); 
+0

非常感謝,我怎麼讓#(後跟一個空格)變成

? –

+0

'noHtml.replaceAll(「#([^ \\ s] +)」,「

$ 1

」);' – jlordo

0

嘗試:

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

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

說你用在散列開始和顯着的字或詞,你可以的年底使用這樣的方法可以在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(); 
} 

如果你叫

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

它將返回

"<h1>My Title One!</h1> non title text, <h1>One more</h1>" 
+0

你爲什麼要改變問題以適合你的答案。 OP特意詢問一個#。而不是這麼長的代碼,Jakub的答案看起來很完美。 – Arham

+1

完全同意。但我試圖讓OP認爲它可以幫助延長。如果他們想要一個帶有一些h1和一些普通文本的字符串呢?或給定的字符串多個h1文本? – jakson

+1

此外,此方法可能會稍微改變,您可以處理給定的字符串,並標記所有粗體文本,斜體文本,不同標題大小等。 – jakson

相關問題