Scala capture group using regex

后端 未结 5 907
[愿得一人]
[愿得一人] 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

    Here's an example of how you can access group(1) of each match:

    val string = "one493two483three"
    val pattern = """two(\d+)three""".r
    pattern.findAllIn(string).matchData foreach {
       m => println(m.group(1))
    }
    

    This prints "483" (as seen on ideone.com).


    The lookaround option

    Depending on the complexity of the pattern, you can also use lookarounds to only match the portion you want. It'll look something like this:

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

    The above also prints "483" (as seen on ideone.com).

    References

    • regular-expressions.info/Lookarounds
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-13 00:01
    val string = "one493two483three"
    val pattern = """.*two(\d+)three.*""".r
    
    string match {
      case pattern(a483) => println(a483) //matched group(1) assigned to variable a483
      case _ => // no match
    }
    
    0 讨论(0)
  • 2020-12-13 00:02

    You want to look at group(1), you're currently looking at group(0), which is "the entire matched string".

    See this regex tutorial.

    0 讨论(0)
  • 2020-12-13 00:02
    def extractFileNameFromHttpFilePathExpression(expr: String) = {
    //define regex
    val regex = "http4.*\\/(\\w+.(xlsx|xls|zip))$".r
    // findFirstMatchIn/findAllMatchIn returns Option[Match] and Match has methods to access capture groups.
    regex.findFirstMatchIn(expr) match {
      case Some(i) => i.group(1)
      case None => "regex_error"
    }
    }
    extractFileNameFromHttpFilePathExpression(
        "http4://testing.bbmkl.com/document/sth1234.zip")
    
    0 讨论(0)
提交回复
热议问题