[英]Scala capture group using regex
假設我有這段代碼:
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
的類,而不使用unapply?
以下是如何訪問每個匹配的group(1)
的示例:
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).matchData foreach {
m => println(m.group(1))
}
這打印"483"
( 如ideone.com上所示 )。
根據模式的復雜程度,您還可以使用外觀僅匹配所需的部分。 它看起來像這樣:
val string = "one493two483three"
val pattern = """(?<=two)\d+(?=three)""".r
pattern.findAllIn(string).foreach(println)
以上還打印"483"
( 如ideone.com上所示 )。
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
}
你想看看group(1)
,你當前正在查看group(0)
,這是“整個匹配的字符串”。
請參閱此正則表達式教程 。
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")
啟動Scala 2.13
,作為正則表達式解決方案的替代方案,也可以通過取消應用字符串插補器來模式匹配String
:
"one493two483three" match { case s"${x}two${y}three" => y }
// String = "483"
甚至:
val s"${x}two${y}three" = "one493two483three"
// x: String = one493
// y: String = 483
如果您希望不匹配輸入,可以添加默認模式保護:
"one493deux483three" match {
case s"${x}two${y}three" => y
case _ => "no match"
}
// String = "no match"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.