怎样在scala正则表达式提取器中使用小括号

2025-04-15 02:13:28
推荐回答(1个)
回答1:

作者:夏梓耀
链接:https://www.zhihu.com/question/36344037/answer/67061326
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

def unapplySeq(target: Any): Option[List[String]] = target match {
case s: CharSequence =>
val m = pattern matcher s
if (runMatcher(m)) Some((1 to m.groupCount).toList map m.group)
else None
case m: Match => unapplySeq(m.matched)
case _ => None
}
protected def runMatcher(m: Matcher) = m.matches()

m.group(1 to groupCount) 是全取出来了,所以小括号套小括号也没问题:

scala> val SP = "((\\d*) (\\w*))".r
SP: scala.util.matching.Regex = ((\d*) (\w*))

scala> val SP(all, a, b) = "123 abc"
all: String = 123 abc
a: String = 123
b: String = abc