Scala 捕获组使用 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"

/
http://ideone.com/Ooyti
/.

选择回顾

根据模板的复杂性,您也可以使用 lookarounds, 匹配

只要

你想要的一部分。 它看起来像这样:


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


还印刷了上面
"483"

/
http://ideone.com/oPV2l
/.

建议书

http://www.regular-expressions ... .html

小姐请别说爱

赞同来自:

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/

, 也就是说 "the entire matched string".


http://daily-scala.blogspot.co ... .html
.

莫问

赞同来自:

以。。。开始
Scala 2.13

, 解决方案的替代方案 regex, 您还可以匹配模板
String

, 不是
https://www.scala-lang.org/fil ... ntext$s$.html#unapplySeq/s:String/:Option[Seq[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"

窦买办

赞同来自:

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"/

要回复问题请先登录注册