val patterns = Seq(
"the name and age are ([a-z]+), ([0-9]+)".r,
"name:([a-z]+),age:([0-9]+)".r,
"n=([a-z]+),a=([0-9]+)".r
)
def transform(subject: String): Option[String] = {
patterns.map(_.unapplySeq(subject)).collectFirst { case Some(List(name, age)) => s"$name$age" }
}
println(transform("name:joe,age:42")) // Some(joe42)
This code that finds and transforms the first match in a list of regexes can be improved by returning early for the average case
What is the best way to make patterns a lazy collection taking into consideration performance and thread safety? Can a view be reused by multiple threads or should a new view be created for each invocation of transform?
patterns.viewpatterns.to(LazyList)
I still feel that there could be advantages when using a single regex pattern.