Scala: extracting part of a Strings using Regular Expressions

scala> val s = "Some(1234)"
s: String = Some(1234)

scala> val nums = "[0-9]".r
nums: scala.util.matching.Regex = [0-9]

scala> nums.findAllIn(s).mkString
res0: String = 1234

Starting Scala 2.13, it's possible to pattern match a Strings by unapplying a string interpolator:

val s"Some($number)" = "Some(1234)"
// number: String = 1234

Also note that if the idea is to extract an Option[Int] from its toString version, you can use the interpolation extraction with a match statement:

x match { case s"Some($number)" => number.toIntOption case _ => None }
// x = "Some(1234)"     =>     Option[Int] = Some(1234)
// x = "Some(1S3R)"     =>     Option[Int] = None
// x = "None"           =>     Option[Int] = None

val s = "Some(1234)"
//s: java.lang.String = Some(1234)

val Pattern = """Some\((\d+)\)""".r
//Pattern: scala.util.matching.Regex = Some\((\d+)\)

val Pattern(number) = s
//number: String = 1234

Switch out your regex for whatever you need. \d+ limits it to digits only.

Tags:

Regex

Scala