Last active
December 16, 2015 03:09
-
-
Save fumokmm/5367413 to your computer and use it in GitHub Desktop.
「GroovyでMarkdownパーサーを作ろう」
http://npnl.hatenablog.jp/entry/series/fumomarkdowng
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 第一引数の内容を読み込む | |
def lines = new File(args[0]).readLines() | |
// Markdown形式をHTMLに変換 | |
def md = new Markdown() | |
def contents = lines.collect { | |
md.headerAtx(it) | |
}.join('\n') | |
// 読み込んだ内容をHTMLのテンプレートに流し込む | |
println """<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="utf-8"> | |
<title>fumomarkdowng</title> | |
</head> | |
<body> | |
${contents} | |
</body> | |
</html>""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="utf-8"> | |
<title>fumomarkdowng</title> | |
</head> | |
<body> | |
<h1>level1</h1> | |
<h2>level2</h2> | |
<h3>level3</h3> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Markdown { | |
/** 見出し:Atx形式 */ | |
String headerAtx(String md) { | |
def sharpSize = md.find(/^#+/).size() | |
if (sharpSize in 1..6) { | |
def tags = [ "<h${sharpSize}>", | |
"</h${sharpSize}>" ] | |
//def contents = md.replaceAll(/^#+\s*|\s*#+$/, '').trim() | |
def contents = md.replaceAll(/(?x) # enable whitespace and comments | |
^\#+ # 先頭からはじまるシャープ | |
| # または | |
\#+$ # 最後のシャープ | |
/, '').trim() | |
return "${tags.first()}${contents}${tags.last()}" | |
} else { | |
return md | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment