Dmitry Zinkevich
Dmitry Zinkevich

Reputation: 3623

Why does Scala regexp work differently in pattern matching

I have a simple regular expression val emailRegex = "\\w+@\\w+\\.\\w+".r that matches simple emails (not for production, of course:). When I run the following code:

println(email match {
  case emailRegex(_) => "cool"
  case _ => "not cool"
})

printlnemailRegex.pattern.matcher(email).matches())

It prints not cool and true. Adding anchors doesn't help either: "^\\w+@\\w+\\.\\w+$".r gives the same result. But when I add parentheses "(\\w+@\\w+\\.\\w+)".r it prints cool and true.

Why does this happen?

Upvotes: 1

Views: 127

Answers (2)

sepp2k
sepp2k

Reputation: 370142

The number of arguments to a regex pattern should match the number of capturing group in the regex. Your regex does not have any capturing groups, so there should be zero arguments:

println(email match {
  case emailRegex() => "cool"
  case _ => "not cool"
})

printlnemailRegex.pattern.matcher(email).matches())

Upvotes: 6

Benjamin Vialatou
Benjamin Vialatou

Reputation: 626

Because pattern matching with a regex is about capturing regex groups:

val email = "[email protected]"
val slightyDifferentEmailRegex = "(\\w+)@\\w+\\.\\w+".r // just add a group with two brackets
println(email match {
  case slightyDifferentEmailRegex(g) => "cool" + s" and here's the captured group: $g"
  case _ => "not cool"
})

prints:

cool and here's the captured group: foo

Upvotes: 5

Related Questions