簡體   English   中英

Scala regex模式與字符串插值匹配

[英]Scala regex pattern matching with String Interpolation

在Scala 2.10中,我們可以使用StringContext定義新方法r,如下所示:

implicit class RegexContext(sc: StringContext) {
  def r = new Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}

然后,我們可以在case關鍵字之后輕松定義正則表達式模式,如下所示:

"123" match { 
   case r"\d+" => true 
   case _ => false 
}

我不清楚這在隱式類RegexContext內部的實現是如何工作的

有人可以向我解釋方法r的實現,尤其是sc.parts.tail.map(_ => "x"): _*嗎?

該實現取自如何在Scala中使用正則表達式進行模式匹配?

這些參數是組名,在這里不是很有用。

scala 2.13.0-M5> implicit class R(sc: StringContext) { def r = sc.parts.mkString.r }
defined class R

scala 2.13.0-M5> "hello" match { case r"hell.*" => }

相比:

scala 2.13.0-M5> implicit class R(sc: StringContext) { def r = sc.parts.mkString("(.*)").r }
defined class R

scala 2.13.0-M5> "hello" match { case r"hell$x" => x }
res5: String = o

Regex構造函數帶有兩個參數。

新的正則表達式 (正則表達式:字符串,組名:字符串*)

groupNames參數是一個vararg,因此它(它們)實際上是可選的,在這種情況下,應將其保留為空,因為groupNames代碼幾乎沒有用。

讓我們回顧一下groupNames應該做什么。 我們將從沒有groupNames開始。

val rx = new Regex("~(A(.)C)~")  // pattern with 2 groups, no group names
rx.findAllIn("~ABC~").group(0) //res0: String = ~ABC~
rx.findAllIn("~ABC~").group(1) //res1: String = ABC
rx.findAllIn("~ABC~").group(2) //res2: String = B
rx.findAllIn("~ABC~").group(3) //java.lang.IndexOutOfBoundsException: No group 3

現在有了groupNames

val rx = new Regex("~(A(.)C)~", "x", "y", "z")  // 3 groups named
rx.findAllIn("~ABC~").group("x") //res0: String = ABC
rx.findAllIn("~ABC~").group("y") //res1: String = B
rx.findAllIn("~ABC~").group("z") //java.lang.IndexOutOfBoundsException: No group 3

那么,為什么sc.parts.tail.map(_ => "x"): _*這么沒用? 首先是因為創建的名稱數量與模式中的組數量無關,而且還因為它為指定的每個名稱都使用相同的字符串"x" 該名稱僅對最后一個命名的組有用。

val rx = new Regex("~(A(.)C)~", "x", "x")  // 2 groups named
rx.findAllIn("~ABC~").group("x") //res0: String = B (i.e. group(2))

...和...

val rx = new Regex("~(A(.)C)~", "x", "x", "x")  // 3 groups named
rx.findAllIn("~ABC~").group("x") //java.lang.IndexOutOfBoundsException: No group 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM