Geo*_*Geo 63 regex string scala capturing-group
假设我有这段代码:
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).foreach(println)
Run Code Online (Sandbox Code Playgroud)
我希望findAllIn只返回483,但相反,它返回了two483three.我知道我可以使用unapply只提取那部分,但我必须有一个整个字符串的模式,如:
val pattern = """one.*two(\d+)three""".r
val pattern(aMatch) = string
println(aMatch) // prints 483
Run Code Online (Sandbox Code Playgroud)
有没有另一种方法来实现这一点,而不使用java.util直接的类,而不使用unapply?
pol*_*nts 93
以下是您可以访问group(1)每场比赛的示例:
val string = "one493two483three"
val pattern = """two(\d+)three""".r
pattern.findAllIn(string).matchData foreach {
m => println(m.group(1))
}
Run Code Online (Sandbox Code Playgroud)
打印"483"(如ideone.com上所示).
根据模式的复杂程度,您还可以使用外观仅匹配所需的部分.它看起来像这样:
val string = "one493two483three"
val pattern = """(?<=two)\d+(?=three)""".r
pattern.findAllIn(string).foreach(println)
Run Code Online (Sandbox Code Playgroud)
以上也打印"483"(如ideone.com上所示).
cai*_*cuk 32
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
}
Run Code Online (Sandbox Code Playgroud)
Xav*_*hot 18
首先Scala 2.13,作为正则表达式解决方案的替代方案,还可以String通过不应用字符串插值器来模式匹配 a :
"one493two483three" match { case s"${x}two${y}three" => y }
// String = "483"
Run Code Online (Sandbox Code Playgroud)
甚至:
val s"${x}two${y}three" = "one493two483three"
// x: String = one493
// y: String = 483
Run Code Online (Sandbox Code Playgroud)
如果您希望不匹配的输入,您可以添加一个默认的模式保护:
"one493deux483three" match {
case s"${x}two${y}three" => y
case _ => "no match"
}
// String = "no match"
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45849 次 |
| 最近记录: |