Scala Parser Combinators空格匹配问题:not与后续内容未区分空格
修正Scala Parser Combinators中"not"与标识符的匹配冲突
你的问题根源在于:Scala Parser Combinators的字符串匹配默认是子串匹配,而非独立单词匹配。当输入"note(p2)"时,解析器会优先匹配开头的"not"子串,把剩余的"e(p2)"当作fol_condition的一部分,最终生成错误的Negation实例。
解决方案1:用正则表达式匹配完整的"not"单词
通过正则表达式的单词边界\b确保"not"是一个独立的单词,不会匹配"note"这类包含"not"前缀的标识符:
def fol_negation : Parser[Negation] = """not\b""".r ~ fol_condition ^^ {case _~sub => Negation(sub)}
解决方案2:使用词法分析器标记保留关键字(更推荐)
对于复杂的解析场景,建议显式区分关键字和标识符,使用StandardTokenParsers定义词法规则,将"not"标记为保留字:
import scala.util.parsing.combinator.syntactical.StandardTokenParsers object FOLParser extends StandardTokenParsers { // 定义保留关键字 lexical.reserved += "not" // 定义语法分隔符 lexical.delimiters += ("(", ")", ",") def fol_condition: Parser[Condition] = fol_negation | fol_predicate def fol_negation: Parser[Negation] = "not" ~ fol_condition ^^ { case _ ~ sub => Negation(sub) } def fol_predicate: Parser[Predicate] = ident ~ "(" ~ repsep(ident, ",") ~ ")" ^^ { case name ~ _ ~ args ~ _ => Predicate(name, args) } }
这种方式下,词法分析器会先识别"not"作为关键字,而"note"会被解析为普通标识符,彻底避免前缀匹配的冲突问题。
内容的提问来源于stack exchange,提问作者Luca Sabatucci
相关产品推荐
相关产品推荐

