12

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 4

11
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.

Sign up to request clarification or add additional context in comments.

3 Comments

what if it didn't match ?
A scala.MatchError will be thrown.
I have multiple parenthesis-pairs, how do I get the correct match?
7
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

Comments

3

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

Comments

0

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)
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.