Scala外部DSL-多行字符串文字 [英] Scala External DSL -- Multi line string literal
问题描述
我正在尝试使用scala解析器组合器定义外部DSL。我发现'stringLit'令牌解析器不能使用三重引号来容纳多行字符串。 Scala解析器组合器世界中是否有类似于multiLineStringLit的东西?
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?
预先感谢,
Kishore
Thanks in advance, Kishore
推荐答案
不是我所知道的,但是编写自己的并不难:
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
}
这只是 stringLiteral
进行了一些小修改:我将分隔符从
更改为
,并添加了 \n
匹配字符。
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."""
这与Scala的多行字符串文字的实现不完全匹配(您不能例如,字符串中未转义的
),但可以轻松对其进行调整,并且可能对您有用。
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.
这篇关于Scala外部DSL-多行字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!