blue-sky
blue-sky

Reputation: 53876

Using regex with filter in Scala

The use of below regex does not match value : charIntIntIntIntIntInt :

val regex = "([a-zA-Z]\\d\\d\\d\\d\\d\\d)"
       //> regex  : String = ([a-zA-Z]\d\d\d\d\d\d)
val f = List("b111111").filter(fi => fi startsWith regex)
       //> f  : List[String] = List()

f is an empty List, it should contain b111111

When I use this regex on https://www.regex101.com/ then it correctly matches the String.

Is there a problem with how I'm filtering ?

Upvotes: 10

Views: 12743

Answers (2)

oalyman
oalyman

Reputation: 311

How about using the Scala language Regex features like:

val regex = """^([a-zA-Z]\d{6})""".r // enables you to drop escaping \'s
val f = List("b111111").filter { s => regex.findFirstIn(s).isDefined }

see http://www.scala-lang.org/api/current/index.html#scala.util.matching.Regex for more details

Upvotes: 14

blue-sky
blue-sky

Reputation: 53876

Need to use matches instead of startsWith

This is detailed in String.class

This works :

val regex = "([a-zA-Z]\\d\\d\\d\\d\\d\\d)" 
val f = List("b111111").filter(fi => fi matches regex)

Upvotes: 15

Related Questions