我正在尝试使用 (<, <=, >=, >) 解析表达式。除了 <= 之外的所有工作都很好。有人可以帮忙可能是什么问题。
代码:
object MyTestParser extends RegexParsers {
override def skipWhitespace = true
private val expression: Parser[String] = """[a-zA-Z0-9\.]+""".r
val operation: Parser[Try[Boolean]] =
expression ~ ("<" | "<=" | ">=" | ">") ~ expression ^^ {
case v1 ~ op ~ v2 => for {
a <- Try(v1.toDouble)
b <- Try(v2.toDouble)
} yield op match {
case "<" => a < b
case "<=" => a <= b
case ">" => a > b
case ">=" => a >= b
}
}
}
测试:
"MyTestParser" should {
"successfully parse <= condition" in {
val parser = MyTestParser.parseAll(MyTestParser.operation, "10 <= 20")
val result = parser match {
case MyTestParser.Success(s, _) => s.get
case MyTestParser.Failure(e, _) =>
println(s"Parsing failed with error: $e")
false
case MyTestParser.Error(e, _) =>
println(s"Parsing error: $e")
false
}
result === true
}
"successfully parse >= condition" in {
val result = MyTestParser.parseAll(MyTestParser.operation, "50 >= 20").get
result === scala.util.Success(true)
}
}
<= 条件的错误:
Parsing failed with error: string matching regex `[a-zA-Z0-9\.]+' expected but `=' found
最佳答案
您需要更改选项的顺序,以便可以首先检查最长的选项。
expression ~ ( "<=" | ">=" | ">" | "<") ~ expression ^^ {
如果最短的备选方案首先匹配,则根本不考虑其他备选方案。
另请注意,不必在字符类中转义句点,这将执行以下操作:
"""[a-zA-Z0-9.]+""".r
关于regex - 小于等于运算符 (<=) 的 Scala 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33262453/