Given a regex and a string
val reg = "(a)(b)"
val str = "ab"
and a corresponding case class
case class Foo(a: string, b: string)
How can I match the regex against the string and unapply the matches into the case class so I have
Foo("a", "b")
in the end?
Pattern match on the result of finding the regular expression in the string and assigning the results to Foo
. The API docs for Regex have a similar example.
scala> val reg = "(a)(b)".r
reg: scala.util.matching.Regex = (a)(b)
scala> val str = "ab"
str: String = ab
scala> case class Foo(a: String, b: String)
defined class Foo
scala> val foo = reg.findFirstIn(str) match{
| case Some(reg(a,b)) => new Foo(a,b)
| case None => Foo("","")
| }
foo: Foo = Foo(a,b)
scala> foo.a
res2: String = a
scala> foo.b
res3: String = b
If you are sure that the match is ok, you can currify the function and use a foldleft to apply this version to the list of extracted arguments:
> val reg = "(a)(b)".r
> val str = "ab"
> val f1 = (Foo.apply _).curried
// f1 : String => String => Foo
> val groups = reg.findFirstMatchIn(str).get.subgroups
// groups: List[String]
> val foo = ((f1 : Any) /: groups) { case (f: (String => Any), s) => f(s)} asInstanceOf[Foo]
foo: Foo = Foo(a,b)
See Function2 in scala for the definition of curried.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.