我想使用regex.findAllMatchIn和Iterator [Match]匹配下面的支撐文本。以下代碼顯示在某些情況下matchesOne的長度非零,但接着說它是空的迭代器。我覺得我在這裏錯過了一些基本的東西。有什麼想法嗎?爲什麼在Scala中,我的Iterator [Match]給出了一個長度,但沒有數據?
import scala.util.matching.Regex.Match
import scala.xml._
val xmldata = <document>
<content>
<headers>
</headers>
<body>
Foo [1], then another foo[2]; then lots of other things here
And add a few other lines[2][3] of test data[3][5] (Foo 1234)
</body>
</content>
</document>
val bodyIterator : Iterator[String]= ((xmldata \ "content" \ "body").text).linesWithSeparators
while (bodyIterator.hasNext) {
val line = bodyIterator.next()
println(s"***** Line is: $line")
val citationOne = """(\[[0-9]+\])(,\[[0-9]+\])*""".r
val citationTwo = """(\([A-Z, -.]+[0-9]{4}\))""".r
/* search the line for citations */
val matchesOne: Iterator[Match] = citationOne.findAllMatchIn(line)
val matchesTwo: Iterator[Match] = citationTwo.findAllMatchIn(line)
println("matchesOne found: " + matchesOne.length)
println("matchesTwo found: " + matchesTwo.length)
for (m <- matchesOne) {println(s"match is $m")}
println("matchesOne Matches: ")
matchesOne.foreach(x => println("1: " + x.matched))
//while (matchesOne.hasNext) {
// println("matchesOne: " + matchesOne.next())
// }
while (matchesTwo.hasNext) {
println("matchesTwo: " + matchesTwo.next().matched)
}
println("\n\n")
}
輸出:
import scala.util.matching.Regex.Match
import scala.xml._
xmldata: scala.xml.Elem = <document>
<content>
<headers>
</headers>
<body>
Foo [1], then another foo[2]; then lots of other things here
And add a few other lines[2][3] of test data[3][5] (Foo 1234)
</body>
</content>
</document>
bodyIterator: Iterator[String] = non-empty iterator
***** Line is:
matchesOne found: 0
matchesTwo found: 0
matchesOne Matches:
***** Line is: Foo [1], then another foo[2]; then lots of other things here
matchesOne found: 2
matchesTwo found: 0
matchesOne Matches:
***** Line is: And add a few other lines[2][3] of test data[3][5] (Foo 1234)
matchesOne found: 4
matchesTwo found: 0
matchesOne Matches:
***** Line is:
matchesOne found: 0
matchesTwo found: 0
現在所有的設置。感謝大家!! – 2014-09-23 20:30:27