Scala External DSL — Multi line string literal

流过昼夜 提交于 2020-01-04 02:44:57

问题


I am trying to define an external DSL using the scala parser combinators. I see that the 'stringLit' token parser does not accomodate multi line strings using the triple quotes. Is there something similar to a multiLineStringLit in the scala parser combinator world?

Thanks in advance, Kishore


回答1:


Not that I'm aware of, but it's not too hard to write your own:

import scala.util.parsing.combinator._

object myParser extends JavaTokenParsers {
  def mlStringLiteral: Parser[String] = (
    "\"\"\"" +
    """(\n|[^"\p{Cntrl}\\]|\\[\\/bfnrt]|\\u[a-fA-F0-9]{4})*""" +
    "\"\"\""
  ).r
}

This is just stringLiteral with a couple of minor edits: I've changed the delimiter from " to """ and added \n to the character match.

scala> val s = "\"\"\"This is a multi-\nline string literal.\"\"\""
s: java.lang.String = 
"""This is a multi-
line string literal."""

scala> myParser.parseAll(myParser.mlStringLiteral, s)
res0: myParser.ParseResult[String] = 
[2.24] parsed: """This is a multi-
line string literal."""

It's not an exact match for Scala's implementation of multi-line string literals (you can't have an unescaped " in the string, for example), but it can easily be tweaked, and may work for you as it is.



来源:https://stackoverflow.com/questions/11889081/scala-external-dsl-multi-line-string-literal

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