简体   繁体   中英

Pattern matching with regexes in Scala

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM