使用List [String]和我想要模式化的几个解析器将List中的每个String与解析器匹配。所以它看起来像这样(警告,伪代码):
myStringList.map{
case MyParser.keyword => keyword match {
case KeywordParser.keyword1 => //it's special keyword1
case KeywordParser.keyword2 => //special treatment for keyword2
case NotSpecial => //it's a usual command
}
case MyParser.stringValue => //etc...
}
为什么我要这样做?
我正在解析一个简单的脚本行,其中包含" strings"和$(关键字)。有些关键字很特殊,需要单独处理。 目前我只有一个特殊关键字,所以我使用链式parseAll并匹配,但感觉不对。
那么,怎么做呢?
答案 0 :(得分:0)
它不是真的支持,但你可以这样做:
val parseKeyword: PartialFunction[String, ... ] {
case KeywordParser.keyword1 => //it's special keyword1
case KeywordParser.keyword2 => //special treatment for keyword2
case NotSpecial => //it's a usual command
}
myStringList.map{
case x@MyParser.keyword if parseKeyword.isDefinedAt(x) => parseKeyword(x)
case MyParser.stringValue => //etc...
}
答案 1 :(得分:0)
case class SpecialKeyword1(value: String)
case class SpecialKeyword2(value: String)
...
case class SpecialKeywordN(value: String)
case class SimpleKeyword(value: String)
object MyParser extends JavaTokenParsers{
def expression: Parser[Any] = ...
def keyword1: Parser[SpecialKeyword1] = ...
def keyword2: ...
...
def simplekeyword: Parser[SimpleKeyword] = ...
}
object Main {
def parseScript(inputScript: String): String = {
MyParser.parseAll(MyParser.expression, inputScript) match {
case Success(result, _) => {
case SpecialKeyword1(val) => ...
case SpecialKeyword2(val) => ...
...
case SimpleKeyword(val) => ...
case str: String => ...
}
case Failure(_, _) => "Parsing Failure"
case Error(_, _) => "Parsing Error"
}
}
}