Scala: extracting part of a Strings using Regular Expressions

Viewed 11942

I have a very simple string like this one:

"Some(1234)"

I'd like to extract "1234" out from it. How can I do it?

4 Answers

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

just another way, playing with the regex. Limit to 4 digits.

def getnumber (args: Array[String]) {

  val str = "Some(1234)"
  val nums = "\\d{4}".r
  println (nums.findAllIn(str).mkString)
  }
Related