2011-08-28 30 views
2

在Scala 2.7.7中獲得Regex.MatchIterator大小的最優雅方式是什麼?在Scala 2.7.7中獲取Regex.MatchIterator的大小?

我試過如下:

¤ scala 
Welcome to Scala version 2.7.7final (OpenJDK 64-Bit Server VM, Java 1.6.0_20). 
Type in expressions to have them evaluated. 
Type :help for more information. 

scala> "a".r.findAllIn("a").size 
<console>:5: error: value size is not a member of scala.util.matching.Regex.MatchIterator 
     "a".r.findAllIn("a").size 
          ^

scala> "a".r.findAllIn("a").size() 
<console>:5: error: value size is not a member of scala.util.matching.Regex.MatchIterator 
     "a".r.findAllIn("a").size() 
          ^
+0

我沒有做斯卡拉2.7.7,但你的例子作品在以後的版本中斯卡拉。你嘗試過'長度'嗎? –

+0

是的,我也嘗試過'length': 'scala>「a」.r.findAllIn(「a」).length' ':5:error:值的長度不是scala.util.matching的成員.Regex.MatchIterator' –

回答

3

您可以轉換的迭代器:

iter.toList.size 

一定要保存轉換後的迭代器(如果你想計算的大小後,訪問數據),因爲它只能迭代一次。

而是轉換爲另一個集合,您還可以使用foldLeft的:

(0 /: iter) { case (sum, _) => sum+1 }