Parsing 无法使用regex和Scala解析器组合符分析复杂语言
作为研究的一部分,我正试图为某种语言编写解析器。目前,我在以我想要的方式运行以下代码时遇到问题:Parsing 无法使用regex和Scala解析器组合符分析复杂语言,parsing,scala,parser-combinators,Parsing,Scala,Parser Combinators,作为研究的一部分,我正试图为某种语言编写解析器。目前,我在以我想要的方式运行以下代码时遇到问题: private def _uw: Parser[UW] = _headword ~ _modifiers ~ _attributes ^^ { case hw ~ mods ~ attrs => new UW(hw, mods, attrs) } private def _headword[String] = "\".*\"".r | "[^(),]*".r private def _
private def _uw: Parser[UW] = _headword ~ _modifiers ~ _attributes ^^ {
case hw ~ mods ~ attrs => new UW(hw, mods, attrs)
}
private def _headword[String] = "\".*\"".r | "[^(),]*".r
private def _modifiers: Parser[List[UWModifier]] = opt("(" ~> repsep(_modifier, ",") <~ ")") ^^ {
case Some(mods) => mods
case None => List[UWModifier]()
}
private def _modifier: Parser[UWModifier] = ("[^><]*".r ^^ (RelTypes.toRelType(_))) ~ "[><]".r ~ _uw ^^ {
case (rel: RelType) ~ x ~ (uw: UW) => new UWModifier(rel, uw)
}
private def _attributes: Parser[List[UWAttribute]] = rep(_attribute) ^^ {
case Nil => List[UWAttribute]()
case attrs => attrs
}
private def _attribute: Parser[UWAttribute] = ".@" ~> "[^>.]*".r ^^ (new UWAttribute(_))
因此,如果标题词以“
”开头和结尾,则双引号内的所有内容都被视为标题词的一部分。所有以@
开头的词,如果不在双引号内,都是标题词的属性
例如,在test5中,解析器应将test5.
解析为标题词,并将attr
解析为属性。Just.@被省略,并且前面的所有点都应包含在标题词中
因此,在标题词之后可以有属性和/或修饰语。顺序很严格,因此属性总是在修饰语之后。如果有属性但没有修饰语,则在@
之前的所有内容都被视为标题词的一部分
主要的问题是“[^@(]*”.r
。我尝试过各种创造性的选择,比如”(^[\\w\\.]*)((\\\.\\\\@)\$)”.r
,但似乎什么都不起作用。向前看或向后看如何影响解析器组合器?我不是解析或正则表达式方面的专家,所以欢迎所有帮助!“[^@(]*“.r
与您的问题有关。我发现:
private def _headword[String] = "\".*\"".r | "[^(),]*".r
这是\u uw
中的第一件事(顺便说一句,不建议在Scala中的名称中使用下划线),因此当它尝试解析test5..@attr
时,第二个regexp将匹配所有的
scala> "[^(),]*".r findFirstIn "test5..@attr"
res0: Option[String] = Some(test5..@attr)
因此剩下的解析器将一无所获。此外,\u headword
中的第一个正则表达式也有问题,因为*
将接受引号,这意味着类似的内容将变为有效:
"test6 with a " inside of it..".@attr
至于向前看和向后看,它根本不会影响解析器组合器。正则表达式匹配,或者不匹配——这就是解析器组合器所关心的
"test6 with a " inside of it..".@attr