0

Why doesn't this work?

val isGovt = """Govt .*""".r
val Govt = "Govt 23 foobar"
Govt match {
    case isGovt(_) => println("match works")
    case _ => print("nope. doesn't work")
}

It prints 'nope. doesn't work'. What am I doing wrong?

1 Answer 1

6

Change

val isGovt = """Govt .*""".r

to

val isGovt = """(Govt .*)""".r

When you use a regex as an extractor, the bound variables correspond to the regex's groups. Your regex had none.

You could also simply keep your regex as is and do:

case isGovt() =>

This is probably more like hat you had in mind.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 Or change case isGovt(_) => println("match works") to case isGovt => println("match works")
You meant case isGovt() I guess. Added to my answer, thanks.
@RégisJean-Gilles What if I want to match something like this: """(Govt \\d.*)""".r ? This does not seem to work for say "Govt 23 foobar"
Your regex is wrong: you doubled the backslash but you should not because you are already using triple-quotes, which don't require escaping. Try """(Govt \d.*)""".r

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.