代码之家  ›  专栏  ›  技术社区  ›  Geo

使用regex的scala捕获组

  •  59
  • Geo  · 技术社区  · 15 年前

    假设我有这个代码:

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

    我期待 findAllIn 只返回 483 但是,它却回来了 two483three . 我知道我可以用 unapply 只提取那个部分,但我必须有整个字符串的模式,比如:

     val pattern = """one.*two(\d+)three""".r
     val pattern(aMatch) = string
     println(aMatch) // prints 483
    

    有没有其他方法可以做到这一点,而不使用 java.util 直接使用,不使用?

    4 回复  |  直到 6 年前
        1
  •  88
  •   polygenelubricants    15 年前

    下面是一个如何访问的示例 group(1) 每场比赛:

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

    这张照片 "483" ( as seen on ideone.com )


    环视选项

    根据模式的复杂性,还可以使用lookarounds 只有 匹配您想要的部分。它看起来像这样:

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

    上面也打印了 “483” ( as seen on ideone.com )

    工具书类

        2
  •  27
  •   caiiiycuk    9 年前
    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
    }
    
        3
  •  13
  •   Stephen    15 年前

    你想看看 group(1) ,您当前正在查看 group(0) ,即“整个匹配字符串”。

    this regex tutorial .

        4
  •  1
  •   Gaurav Khare    6 年前
    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")
    
    推荐文章