在Scala 2.7.7中获取Regex.MatchIterator的大小?

时间:2011-08-28 18:30:40

标签: regex scala iterator

在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()
                            ^

1 个答案:

答案 0 :(得分:3)

您可以转换迭代器:

iter.toList.size

确保保存已转换的迭代器(如果要在计算大小后访问数据),因为它只能迭代一次。

您也可以使用foldLeft:

,而不是转换为其他集合
(0 /: iter) { case (sum, _) => sum+1 }