为什么这个scala正则表达式匹配失败?

时间:2012-05-08 21:00:47

标签: regex scala

我有以下简单的应用程序:

object TestPatternMatch extends App {

  if (args.length != 1)
    throw new IllegalArgumentException("takes one argument which is a regex string that will be used to limit the org deletion")

  val pattern = args(0).r
  println("looking for orgs with name matching regex: " + pattern)

  val orgs = Seq("zephyr-test-123", "abcdef", "zephyr-test-xyz-xyz-xyz")

  orgs.foreach {
    _ match {
      case pattern(x) ⇒ println("matched " + x)
      case y          ⇒ println("failed to match " + y)
    }
  }
}

当我在下面打电话时,我期待在第一和第三组织上匹配。我错过了什么?

[info] Running TestPatternMatch zephyr-test-.*
looking for orgs with name matching regex: zephyr-test-.*
failed to match zephyr-test-123
failed to match abcdef
failed to match zephyr-test-xyz-xyz-xyz

1 个答案:

答案 0 :(得分:8)

您的模式不包含匹配()组的x

val R0 = "zephyr-test-.*".r
val R0() = "zephyr-test-123"    // matches, with no assignments
val R0(x) = "zephyr-test-123"   // MatchError, nothing to bind `x` to

val R1 = "zephyr-test-(.*)".r
val R1(x) = "zephyr-test-123"   // matches, x = "123"