Scala capture group using regex

后端 未结 5 929
[愿得一人]
[愿得一人] 2020-12-12 23:42

Let\'s say I have this code:

val string = \"one493two483three\"
val pattern = \"\"\"two(\\d+)three\"\"\".r
pattern.findAllIn(string).foreach(println)
         


        
5条回答
  •  忘掉有多难
    2020-12-13 00:00

    Starting Scala 2.13, as an alternative to regex solutions, it's also possible to pattern match a String by unapplying a string interpolator:

    "one493two483three" match { case s"${x}two${y}three" => y }
    // String = "483"
    

    Or even:

    val s"${x}two${y}three" = "one493two483three"
    // x: String = one493
    // y: String = 483
    

    If you expect non matching input, you can add a default pattern guard:

    "one493deux483three" match {
      case s"${x}two${y}three" => y
      case _                   => "no match"
    }
    // String = "no match"
    

提交回复
热议问题