Is there a simple way to return regex matches as an array?
Here is how I am trying in 2.7.7:
val s = """6 1 2"""
val re = """(\d+)\s(\d+)\s(\d+)""".r
for (m <- re.findAllIn (s)) println (m) // prints "6 1 2"
re.findAllIn (s).toList.length // 3? No! It returns 1!
But I then tried:
s match {
case re (m1, m2, m3) => println (m1)
}
And this works fine! m1 is 6, m2 is 1, etc.
Then I found something that added to my confusion:
val mit = re.findAllIn (s)
println (mit.toString)
println (mit.length)
println (mit.toString)
That prints:
non-empty iterator
1
empty iterator
The “length” call somehow modifies the state of the iterator. What is going on here?
Ok, first of all, understand that
findAllInreturns anIterator. AnIteratoris a consume-once mutable object. ANYTHING you do to it will change it. Read up on iterators if you are not familiar with them. If you want it to be reusable, then convert the result of findAllIn into aList, and only use that list.Now, it seems you want all matching groups, not all matches. The method
findAllInwill return all matches of the full regex that can be found on the string. For example:See that there are two matches, and neither of them include the “, ” at the middle of the string, since that’s not part of any match.
If you want the groups, you can get them like this:
Or, using
findAllIn, like this:The
matchDatamethod will make anIteratorthat returnsMatchinstead ofString.