[英]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.