Scalaパーサーコンビネーターを使用する演習として、単純なWikiのようなマークアップパーサーを実装したいと思います。
これを少しずつ解決したいので、最初のバージョンで達成したいのは、単純なインラインリテラルマークアップです。
たとえば、入力文字列が次の場合:
This is a sytax test ``code here`` . Hello ``World``
出力文字列は次のようになります。
This is a sytax test <code>code here</code> . Hello <code>World</code>
私はを使用してこれを解決しようとしRegexParsers
ます、そしてこれが私が今やったことです:
import scala.util.parsing.combinator._
import scala.util.parsing.input._
object TestParser extends RegexParsers
{
override val skipWhitespace = false
def toHTML(s: String) = "<code>" + s.drop(2).dropRight(2) + "</code>"
val words = """(.)""".r
val literal = """\B``(.)*``\B""".r ^^ toHTML
val markup = (literal | words)*
def run(s: String) = parseAll(markup, s) match {
case Success(xs, next) => xs.mkString
case _ => "fail"
}
}
println (TestParser.run("This is a sytax test ``code here`` . Hello ``World``"))
<code>
このコードでは、マークアップを1つだけ含む単純な入力が適切に機能します。次に例を示します。
This is a sytax test ``code here``.
なる
This is a sytax test <code>code here</code>.
しかし、上記の例で実行すると、次のようになります。
This is a sytax test <code>code here`` . Hello ``World</code>
これは、私が使用する正規表現が原因だと思います。
"""\B``(.)*``\B""".r
``
ペア で任意の文字を許可しました。
``
ネストできなかったものを制限してこの問題を修正する必要があるかどうかを知りたいですか?