blue-sky
blue-sky

Reputation: 53806

Regex not matching

I expect regex "[a-zA-Z]\\d{6}" to match "z999999" but it is not matching as an empty List is mapped :

val lines = List("z999999");                      //> lines  : List[String] = List(z999999)

val regex = """[a-zA-Z]\d{6}""".r                 //> regex  : scala.util.matching.Regex = [a-zA-Z]\d{6}

val fi = lines.map(line => line match { case regex(group) => group case _ => "" })
                                                  //> fi  : List[String] = List("")

Is there a problem with my regex or how I'm using it with Scala ?

Upvotes: 1

Views: 1206

Answers (1)

Squidly
Squidly

Reputation: 2717

val l="z999999"
val regex = """[a-zA-Z]\d{6}""".r

regex.findAllIn(l).toList
res1: List[String] = List(z999999)

The regex seems valid.

lines.map( _ match { case regex(group) => group; case _ => "" })
res2: List[String] = List("")

How odd. Let's see what happens with a capturing group around the whole expression we defined in regex.

val regex2= """([a-zA-Z]\d{6})""".r
regex2: scala.util.matching.Regex = ([a-zA-Z]\d{6})
lines.map( _ match { case regex2(group) => group; case _ => "" })
res3: List[String] = List(z999999)

Huzzah.

The unapply method on a regex is for getting the results of capturing groups.

There are other methods on a regex object that just get matches (e.g. findAllIn, findFirstIn, etc)

Upvotes: 4

Related Questions