regex - 小于等于运算符 (<=) 的 Scala 正则表达式

标签 regex scala parser-combinators

我正在尝试使用 (<, <=, >=, >) 解析表达式。除了 <= 之外的所有工作都很好。有人可以帮忙可能是什么问题。
代码:

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/

相关文章:

haskell - 用 `ParsecT` 进行排列解析?

Scala 解析器组合器,大文件问题

c# - 将 html 字符串拆分为 N 部分

scala - Spark : Calculate event end time on 30-minute intervals based on start time and duration values in previous rows

scala - 如何将[Future [A],Future [B]]转换为Future [Either [A,B]]

scala - 如何控制从 Spark DataFrame 写入的输出文件的数量?

scala 组合器解析器保留原始输入

javascript - 使用反向引用的最佳方法是什么?

Javascript:有趣的正则表达式对象名称?

objective-c - 从图形 API URL 获取 Facebook 用户 ID 的正则表达式?