wipman wipman - 4 months ago 16
Scala Question

Match among values of List

I want to write some clean

pattern-matching
code.

I have a
List
of
Regex
:

val myList = List(
".+\\.a".r,
".+\\.b".r,
".+\\.c".r.+
)


I would like to do something approaching the following:

myInputString match {
case matchAnyRegexFromMyList(s) => //do something
}


As an alternative to:

myInputString match {
case regex1(a)|regex2(b)... => //do something
}


Is it at least possible to be more concise?

Answer

If your patterns were not pre-compiled you could combine them when they are compiled.

val myList = List( ".+\\.a"
                 , ".+\\.b"
                 , ".+\\.c" )

val myListRE = myList.mkString("|").r

"blah.b" match {
  case myListRE() => println("hit")
}
Comments