jxstanford
jxstanford

Reputation: 3387

why is this scala regex match failing?

I have the following simple app:

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)
    }
  }
}

When I call it like below, I was expecting to match on the 1st and 3rd orgs. What have I missed?

[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

Upvotes: 1

Views: 249

Answers (1)

dhg
dhg

Reputation: 52681

Your pattern doesn't contain the () needed to match a group for 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"

Upvotes: 8

Related Questions